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>
sandbox
  • 2,631
  • 9
  • 33
  • 39
  • 2
    here is a good solution http://stackoverflow.com/questions/1125482/how-to-impose-maxlength-on-textarea-in-html-using-javascript – Danny Mar 05 '12 at 20:13
  • Have you tried debugging? Code looks ok to me. The event is raised and the length is correct. – Andreas Mar 05 '12 at 20:18

3 Answers3

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'>
Bartek
  • 15,269
  • 2
  • 58
  • 65
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.

Matthew
  • 24,703
  • 9
  • 76
  • 110
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;
        }
    }
Dewfy
  • 23,277
  • 13
  • 73
  • 121