0

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

3 Answers 3

1
var inputs = document.getElementsByTagName('input');
var count = 0;
for(var cpt = 0; cpt < inputs.length; cpt++)
if (inputs[cpt].type == 'text') count++;
alert(count);
Sign up to request clarification or add additional context in comments.

Comments

0
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);

Comments

0

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--)

3 Comments

... but inaccurate, since it will count all types of <input>, not just text boxes.
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
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.