Access an array of HTML input text fields using jQuery or plain Javascript

I want to create a form containing a dynamic number of text input fields. I would like each text field to become part of the array (this would theoretically make it easier for me to scroll through them, especially since I will not know the number of text fields that will eventually exist). HTML code would like something like:

<p>Field 1: <input type="text" name="field[1]" id="field[1]"></p> <p>Field 2: <input type="text" name="field[2]" id="field[2]"></p> <p>Field 3: <input type="text" name="field[3]" id="field[3]"></p> <p>Field 4: <input type="text" name="field[4]" id="field[4]"></p> <p>Field 5: <input type="text" name="field[5]" id="field[5]"></p> 

This data will then be sent to a PHP script and presented as an array - or, at least in theory.

So my first question is: is this possible with HTML? Forms designed to work this way?

If the answer to this question is yes, then how do I go about accessing each of those using jQuery or failing, plain old javascript?

I tried to achieve this using the following jQuery code:

 someval = $('#field[1]').val(); 

and

 someval = $('#field')[1].val(); 

and the following javascript:

 someval = document.getElementById('related_link_url')[1].value; 

But I’m out of luck.

Thanks in advance.

Edit:

I should note that from a Javascript point of view, I had a job where the identifier of each element is something like field_1, field_2, etc. However, I feel that if I can achieve this by placing each text field in an array, it will be more accurate and easier to manage.

+7
javascript jquery arrays html
source share
2 answers

First of all, the id attribute cannot contain the character [ or ] .

There are many ways to get jQuery / plain JavaScript links to these elements. You can use the descendant selector:

 <fieldset id="list-of-fields"> <!-- your inputs here --> </fieldset> $("#list-of-fields input"); document.getElementById("list....").getElementsByTagName("input"); 

You can also use the attribute selector:

 $("input[name^=field]"); 

I'm not sure the only way, but I think in plain JavaScript you will need to extract all input elements ( document.getElementsByTagName ) and then skip the array from these elements and check each element (regardless of whether it has a name attribute, value which begins with field ).

+6
source share

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 an anonymous function for each input element with the class name "fields", with the this pointing to the current element. See http://api.jquery.com/each/ for details.

+9
source share

All Articles