views:

50

answers:

2

I have a form which is dynamic.

That means, the inputs names are changed, and not the same, but they are all the same "TYPE".

So I need to have a javascript which gets all input type="text" and validates them. Is this possible?

If so, how?

All I need to check is so that they are not empty, and that they are only numeric.

Thanks

+1  A: 

Use document.querySelectorAll("input[type=text]") to get the array with all inputs of type "text". You need to iterate through them and validate.

Also note that you will probably want to use something like #container_id input[type=text] to make sure you won't get any nodes that you don't need.

Here is a sample of how your validation should look:

var nodes = document.querySelectorAll("#container_id input[type=text]");
for (var i=0; i<nodes.length; i++)
    if (node.value == "" || !/[0-9.]+/.test(node.value))
        return "invalid.";
return "valid";
Gabi Purcaru
Care to explain the #container_id a little bit more, what is it for?
Camran
What if you have multiple inputs on that page, and you just want those in your form? The first query will return all of them, and that's not what you need. If you want to fetch only the ones in your needed form, use something like `get all child nodes of the node with id "container_id" that are inputs of type text `. Translated into selector query, you get the second version. I'd recommend you take a look into http://www.w3.org/TR/css3-selectors/#selectors , to see how and what you can do with selectors.
Gabi Purcaru
Note: document.querySelectorAll does not work in IE. But you can use jQuery to achieve the same effect in all browsers
Infinity
@Infinity he said he does not use jquery.
Gabi Purcaru
+1  A: 

Something like that:

var inp = document.getElementsByTagName('input');
for(var i in inp){
    if(inp[i].type == "text"){
        if(!/^\d{1,}$/.test(inp[i].value)){
            alert('Invalid value detected');
            inp[i].focus();
            break;
        }
    }
}
dev-null-dweller
wont work, alert doesn't come up
Camran
http://www.jsfiddle.net/U5Y5y/ Works for me in Opera 10,FF 3.6,Chrome 7 and IE 8.
dev-null-dweller
works for me too, safari, ie6+7 , I don't see any reason why it should'nt work
Dr.Molle