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ô
2010-09-24 18:36:07
Thank you friend
naveenkumar
2010-09-24 18:45:57
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
2010-09-24 18:38:15
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
2010-09-24 18:54:31
... but inaccurate, since it will count all types of `<input>`, not just text boxes.
Tim Down
2010-09-24 19:01:06
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
2010-09-24 19:28:44
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
2010-09-24 19:31:06