I\'m looking to create a form which contains a dynamic number of input text boxes. I would like each text box to form part of an array (this would in theory make it easier f
First of all, id
attribute cannot contains [
or ]
character.
There is lots of ways to get jQuery/plain JavaScript references to these elements. You can use descendant selector:
<fieldset id="list-of-fields">
<!-- your inputs here -->
</fieldset>
$("#list-of-fields input");
document.getElementById("list....").getElementsByTagName("input");
You can also use attribute selector:
$("input[name^=field]");
I'm not sure whether that's the only way but I think in plain JavaScript you'll have to fetch all input
elements (document.getElementsByTagName
) and then loop through array of these elements and check each element (whether it has name
attribute which value starts with field
).
Give each element a class and access the group using jQuery:
<p>Field 1: <input type="text" name="field[1]" class="fields"></p>
<p>Field 2: <input type="text" name="field[2]" class="fields"></p>
<!-- etc... -->
jQuery:
$("input.fields").each(function (index)
{
// Your code here
});
This will run the anonymous function on each input
element with a classname of "fields", with the this
keyword pointing to the current element. See http://api.jquery.com/each/ for more info.