Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
185
rated 0 times [  188] [ 3]  / answers: 1 / hits: 32002  / 15 Years ago, wed, february 3, 2010, 12:00:00

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 for me to loop through them, especially as I won't know the number of text fields that will eventually exist). The 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 would then be sent to a PHP script and would be represented as an array - or at least, that's the theory.



So my first question is, is this achievable using HTML? Are forms designed to work that way?



If the answer to that is yes, how would I then go about accessing each of those using jQuery or failing that, plain old JavaScript?



I've attempted 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've not had any luck.



Thanks in advance.



Edit:



I should note that from a Javascript point of view, I've had it working where the ID of each element is something like field_1, field_2 etc. However, I feel that if I can achieve it by placing each text box into an array, it would make for tidier and easier to manage code.


More From » jquery

 Answers
268

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


[#97673] Sunday, January 31, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
micheleb

Total Points: 275
Total Questions: 103
Total Answers: 103

Location: Macau
Member since Sat, Jul 11, 2020
4 Years ago
;