I am working on an ASP.NET project with a resizable textbox that needs to display a character limit below and to the right of the box. The textbox is contained within a specific portion of the page and does not stretch from the left side to the right. As the textbox is resized based on the browser window size and monitor resolution settings, I'm facing difficulty in aligning the character limit text properly.
I have tried aligning the text to the right, but it doesn't work as expected. How can I achieve the desired behavior of always displaying the character limit text below and to the right of the resizable textbox, even when the box is being resized?
I am using Bootstrap for aligning divs in my project.
--- UPDATE ---
Here are some examples of my code and the scripts they generally utilize:
// EXAMPLE 1
<div class="col-md-3 mb-3 ml-2">
@Html.EditorFor(m=> m.Title, new { htmlAttributes = new { @class = "form-control characterlimit", @maxlength = 128 } })
<div class="text-muted col-md-11 mb-3 ml-4 position-absolute" style="font-size: 12px; text-align:right">128 Character Limit</div>
</div>
// EXAMPLE 2
<div class="col-md-6 mb-3 ml-2">
@Html.TextAreaFor(m => m.Description, new { @class = "form-control characterlimit", @rows = 3, @maxlength = 2500 })
<div class="text-muted col-md-3 mb-3 ml-0 position-absolute" style="font-size: 12px; text-align:right">2500 Character Limit</div>
</div>
<script>
$(".characterlimit").keyup(function () {
var box = $(this);
var max = box.attr("maxlength")
var len = box.val().length;
box.next().text((max - len) + " Characters Left");
});
</script>
In general, you would place both your text box and your character limit indicator inside a container, and then align the character limit indicator to the right within that container.
const recalcLength = ta => {
ta.nextElementSibling.innerHTML = (ta.maxLength - ta.value.length) + ' characters left'
}
document.querySelectorAll('textarea').forEach(ta => {
recalcLength(ta)
ta.addEventListener('keypress', evt => {
recalcLength(evt.target)
})
})
body, textarea {
font-family: sans-serif;
font-size: 16px;
}
body {
background: #eee;
}
.s1 {
margin: 0 auto;
background: white;
margin-bottom: 2em;
display: inline-block;
max-width: 100%;
}
textarea {
width: 600px;
height: 5em;
padding: 5px;
box-sizing: border-box;
max-width: 100%;
}
p {
margin: 0;
font-size: 10px;
text-align: right;
}
<span class="s1">
<textarea maxlength="50">Lorem ipsum dolor sit amet</textarea>
<p class="count"></p>
</span>
<br>
<span class="s1">
<textarea maxlength="100">Etiam ullamcorper velit vitae sem pulvinar, dignissim efficitur nulla interdum </textarea>
<p class="count"></p>
</span>