4

I have a problem regarding dynamically generated fields. These fields have different types and their type depends on what is stored on my db (text, select, radio, etc.). They are generated in my PHP script and they have the same name (ans[], which is an array).

<input type='radio' name='ans[]' value='1'>
<input type='radio' name='ans[]' value='2'>
<input type='radio' name='ans[]' value='3'>

<select name='ans[]'>
    <option value='desktop'>Desktop</option>
    <option value='laptop'>Laptop</option>
    <option value='monitor'>Monitor</option>
    <option value='printer'>Printer</option>
</select>

<input type='text' name='ans[]' value=''>

I want to get the input values of each field using JQuery. Is it possible?

1
  • why u used same name for all? use different Commented Apr 26, 2013 at 3:01

2 Answers 2

2
$("[name=ans\\[\\]]").each(function() {
  alert( $(this).val() );
});

This should work.

JSFiddle

Working example above.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks a lot, it worked for me. but i have another question, from the example above, all of the values of each radio button is retrieved. what if i only want to select one of them?
You will probably need to use more than one selector: $("[name=ans\\[\\]][type!=radio]").each(function() { /* do whatever you want with non radio inputs */ } and $("[name=ans\\[\\]][type=radio]:checked").each(function() { /* do whatever you want with checked radio inputs */ } New JSFiddle: jsfiddle.net/VcZWy/2
thanks for your help. i ended up using .filter(':checked') to know the selected radio button, and used parent().find('input[name=dummyAnswer\[\]]') because i had another text box beside the radio button to know the value of the text box
1

There's a number of ways you can get your field values with jQuery that doesn't rely on IDs or classes (although they're usually the best methods).

You can select fields based on their position in the DOM:

CSS nth-child (http://www.w3schools.com/cssref/sel_nth-child.asp)

$('form#myform input:nth-child(2)')

jQuery .each (http://api.jquery.com/jQuery.each/)

$('form#myform input).each( function(){ /* functionality here */ });

This relies on the fields being generated in a fixed order though. What if you generated a label with each of your PHP array items, and used this to identify your individual fields?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.