Search code examples
javascriptregexdhtml

Regexp: How can I find form fields named with specific character sequence in a form using javascript?


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?


Solution

  • 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.