0

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?

mspir
  • 1,664
  • 2
  • 21
  • 34
  • Can you not modify field generation at all? Is the generation performed on the server side? – strager Sep 04 '10 at 11:30
  • And, are you using any frameworks? I'm assuming "no" because you have added the dhtml tag. – strager Sep 04 '10 at 11:31
  • Hi, No, its generated server side, and to make it a bit more complex fields are reloaded using ajax whenever a product or a spec changes in the order form, so the field names change as well. Thats why I needed to find all the price_* fields. – mspir Sep 04 '10 at 11:53
  • I am using jquery. Still not aware of all it's features though (such as regexp as I just found out) – mspir Sep 04 '10 at 11:54

2 Answers2

2

using jQuery you could do it like this:

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

Moin Zaman
  • 25,281
  • 6
  • 70
  • 74
  • 2
    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 Sep 04 '10 at 11:37
  • 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! – mspir Sep 04 '10 at 11:46
2

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
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 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) – mspir Sep 04 '10 at 11:46