0

I tried limiting the user input but it wasn't successful, please guide me where I am making mistake.

JS

<script type="text/javascript"> function countLength() { var maxLength=10; var length = document.getElementById("txt").value.length; if(length>10) { return false; } } </script> 

HTML code

 <form name="formA" id="formA" action="#" > <textarea id="txt" name="txt" onkeyup="countLength()"></textarea> </form> 
2
  • 2
    here is a good solution stackoverflow.com/questions/1125482/… Commented Mar 5, 2012 at 20:13
  • Have you tried debugging? Code looks ok to me. The event is raised and the length is correct. Commented Mar 5, 2012 at 20:18

3 Answers 3

1

Your code basically replicates the maxlength attribute, which seems to work (and I don't think is being deprecated?). Just use that.

<input type='text' name='mytext' maxlength='10'> 
Sign up to request clarification or add additional context in comments.

2 Comments

textareas have no maxlength. That's for input fields only.
Yea I know that but I also want to display message underneath eg: 5 characters left as in stackoverflow textbox
0

return false on onkeyup does nothing (as you've probably noticed). I've seen solutions where someone would just alter the value of the textarea, perform a substring operation, and assign that new value back.

Comments

0

Try this:

 function countLength() { var maxLength=10; var ta = document.getElementById("txt"); var length = ta.value.length; if(length>maxLength) { ta.value = ta.value.substr(0, maxLength); return false; } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.