If you’ve found this page, then chances are you are coming up against the problem where the Javascript .length method is always returning 1 for a jQuery selector. For example, if you have a variable in Javascript, you can ascertain its length as follows:
var myString = "Hello World";
alert(myString.length);
Which should give an output of 11 – i.e. there are 11 characters in the variable. This also applies for variables within jQuery functions. However if you try to apply .length to a selector – e.g.:
alert($('#mySelector').length);
You will always get a return value of 1. What you actually need to do is as follows:
HTML Code:
<div id='mySelector'>Hello World</div>
jQuery Code:
alert($('#mySelector').val().length);
Which will give the expected return value of 11.

Recent Comments