开发者_StackOverflow中文版How can we get number of textboxes in a form using javascript? Thanks in advance.
var inputs = document.getElementsByTagName('input');
var count = 0;
for(var cpt = 0; cpt < inputs.length; cpt++)
if (inputs[cpt].type == 'text') count++;
alert(count);
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);
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--)
精彩评论