Search code examples
javascriptprototypejsprototype

How to select all elements based off of an attribute value containing a string in Prototype


Here's my scenario.

I have the following inputs within a page.

<input name="myInput[field1]" value="field1value" type="text" />

<input name="myInput[field2]" value="field2value" type="text" />

<select name="myInput[select1]">
   <option value="1" selected="selected">Option 1</option>
   <option value="2">Option 2</option>
   <option value="3">Option 3</option>
</select>

Using Prototype, I am trying to select all fields containing myInput within the name attribute and loop through each of them to append their values to a variable, like this:

var myVar = field1Value + field2Value + select1Value;

Is this possible?


Solution

  • The correct solution is the following:

    var myVar;
    $$('[name^="myInput"]').each( function(i) {
       myVar += i.value;        
    });
    

    They key to selecting all inputs, containing myInput in their name attribute is using the ^ symbol before the = sign. So [name^="myInput"] is the correct selector to achieve this.