I have a TextArea and a <span>
in my ASP.NET MVC code:
<div>
@Html.TextAreaFor(m => m.Note, 4, 20,
new {
id = "Note",
name = "textareaNote",
maxlength = "250",
@class = "text-danger form-control",
placeholder = "Enter note here - limited to 250 characters",
onkeyup = "showRemaining(Note, remainingC, 250)"
})
<span id="remainingC"></span>
@Html.ValidationMessageFor(m => m.Note, "", new { @class = "text-danger" })
</div>
Whenever onkeyup
fires, it has an error with the "remainingC" span:
<script type="text/javascript">
function showRemaining(itemX, statusX, maxchar) {
var len = itemX.value.length;
if (maxchar < len) {
return false;
} else if (0 < len) {
statusX.html('Remaining: ' + maxchar - len);
} else {
statusX.html('Remaining: ' + maxchar);
}
}
</script>
Every time I try typing into my textArea, I get this error:
Uncaught TypeError: statusX.html is not a function
I struggle with Javascript.
What do I need to do to get this working?
I got it.
The ASP.NET HTML was fine:
@Html.LabelFor(m => m.Note)
<div>
@Html.TextAreaFor(m => m.Note, 4, 20,
new
{
id = "Note",
name = "textareaNote",
maxlength = 250,
@class = "text-danger form-control",
placeholder = "Enter note here - limited to 250 characters",
onkeyup = "showRemaining(Note, remainingC, 250)"
})
<span id="remainingC"></span>
@Html.ValidationMessageFor(m => m.Note, "", new { @class = "text-danger" })
</div>
Like Pointy pointed out, the issue was with mixing some jQuery syntax with JavaScript.
I wasn't able to get Pointy's innerHTML
to work, but I was able to get textContent
to work:
<script type="text/javascript">
function showRemaining(itemX, statusX, maxchar) {
var len = itemX.value.length;
if (maxchar < len) {
return false;
} else {
var number = 0;
if (0 < len) {
number = maxchar - len;
} else {
number = maxchar;
}
statusX.textContent = 'Remaining: ' + number;
}
}
</script>
Example with less code
<script>
function showRemaining(itemX, statusX, maxchar) {
const len = itemX.value.length;
if (maxchar < len) {
return false;
}
statusX.textContent = 'Remaining: ' + (!!len ? maxchar - len : maxchar);
}
</script>