Setting the maxlength of a textbox to a variable

Viewed 25

I'm attempting to set the maxlength value of a textbox to the length of a string using javascript, but the maxlength doesn't change at all.

<input name="answerTxt" type="text" class="form" id="answer" onkeypress="do_enter(event);" onkeyup="count('answer');" size="25" maxlength="5"> &nbsp; 
<script>
    var txt = "hello"
    document.getElementById('answer').maxlength = txt.length
</script>
1 Answers
document.getElementById('answer').setAttribute("maxlength", txt.length)

You can use setAttribute() function instead. Or if you want to use maxlength property, you must write 'maxLength', not 'maxlength'.

document.getElementById('answer').maxLength = txt.length

I hope you understand.

Related