views:

37

answers:

3

How can we get number of textboxes in a form using javascript? Thanks in advance.

+1  A: 
var inputs = document.getElementsByTagName('input');
var count = 0;
for(var cpt = 0; cpt < inputs.length; cpt++)
if (inputs[cpt].type == 'text') count++;
alert(count);
GôTô
Thank you friend
naveenkumar
A: 
var node_list = document.getElementsByTagName('input');
var c=0;
for (var i = 0; i < node_list.length; i++) {
    var node = node_list[i];

     if (node.getAttribute('type') == 'text') {
        c++;
     }
 } 
alert(c);
rahim asgari
A: 

This will be faster:

Array.prototype.slice.apply(document.getElementsByTagName('input')).length;

But it won't separate input types. If you have to do that, create the array like I did above then loop through the array and select members that are the right type, then check length on the resulting array.

(function () {
    var arr = Array.prototype.slice.apply(document.getElementsByTagName('input')),
    i = arr.length, item, textOnlyArray = [];
    while (i--) {
        item = arr[i];
        if (item.hasOwnProperty("type") && item.type === "text") {
            textOnlyArray.push(item);
        }
    }
    return textOnlyArray;
}());

You can also use Array.forEach if you don't need to support old/junky browsers. That's even faster than while(i--)

AutoSponge
... but inaccurate, since it will count all types of `<input>`, not just text boxes.
Tim Down
hasOwnProperty is so misused... do you use it here because you modified Object's prototype? That's a bad idea in the first place. The real problem with hasOwnProperty is that you lose the ability to check for inherited properties. GôTô's answer is simpler and clearer
Juan Mendes
I'm checking the DOM node's property, so I don't want inherited properties. The Object property was not modified. I think you misunderstand what .apply() does.
AutoSponge