views:

29

answers:

2

Hello,

I have a form which among others contains text inputs that contain arithmetic data (prices) The elements and their names are dynamically generated. I would like to only "find" fields that contain arithmetic values based on their names (i.e. an example element name would be price_500_365 (from price_PRODUCTID_ORDERID). So I want to find all text inputs containing "price" in their names or id's using regexp and sum them up. I am not sure how to do it. Any ideas?

+2  A: 

using jQuery you could do it like this:

$('input[name*="price"]');

Moin Zaman
Including jQuery for this is overkill I believe, since it's just a `for` loop. *Finding* the elements is trivial, the summation isn't made any easier by jQuery IMO, or much shorter. If the author has *other* situations improved by jQuery then by all means, but for this question, it's massive overkill.
Nick Craver
I do have jquery included in the project indeed. A good explanation for the above suggestion is here also http://stackoverflow.com/questions/345194/regular-expression-matching-in-jquery (I just found it). But I was looking something like the solution below. I marked this answer as useful, but I will have to accept the one below. Thank you guys!
Spiros
+2  A: 

You can loop through the form's elements, like this:

var form = document.getElementById("myForm"), sum = 0;
for(var i=0; i<form.elements.length; i++) {
   var e = form.elements[i];
   if(e.type === 'text' && /price/.test(e.name)) sum += parseFloat(e.value);
}
alert(sum);

You can test it here, if you're not dealing with <input> elements strictly though, you may need to change up the if check to include/exclude more elements.

Nick Craver
Thanks, works like a charm! I was unsure of how to check against the names, trying to work with regexp. I was unaware of the test method, learned something new today :o)
Spiros