Reputation: 61
I have got some trouble about doing an loop through the following construct:
<div id="items">
<p id="test1">
<select name="1" id="1"><option>A</option><option selected>B</option></select>
<input type="text" name="to" id="to">
<input type="text" name="away" id="awy">
</p>
<p id="test2">
<select name="2" id="2"><option>A</option><option selected>B</option></select>
<input type="text" name="to" id="to">
<input type="text" name="away" id="awy">
</p>
<p id="test3">
<select name="3" id="3"><option>A</option><option selected>B</option></select>
<input type="text" name="to" id="to">
<input type="text" name="away" id="awy">
</p>
</div>
I need to run through test1, test2 and test3 and read the selected option and the values of the text-fields (select, to,away). Doing this if i got only one thing in for example test1 is no problem with query:
$('#items').children('p').each(function () {...}
But if i add the two text-fields and want to do this for each test (1-3) I have no idea...
Any idea? Thanks!
Upvotes: 1
Views: 407
Reputation: 1339
You dont even need to do the .children
part.
Try this:
$('#items > p').each(function () {
// you can then use $(this) to reference the currently iterated p element.
// such as $(this).find('input[type="text"]:first');
// or
// $(this).find('input[type="text"]:last');
});
Upvotes: 0
Reputation: 345
Note: First of all give the unique id for all elements.
The following code might help you.
$(‘p’).each(function(index){
this.children().get(0).val();
//now do for second and third also
}
Upvotes: 0
Reputation: 13983
Ids should represent unique items within a DOM. Use classes instead, like so:
<input type="text" name="to" class="to">
<input type="text" name="away" class="awy">
Upvotes: 3
Reputation: 12390
How about this?
$('#items').find('select option:selected, input:text').each(function(){
alert($(this).val()); //Value of each selected option and text field within the div
});
Upvotes: 0