Reputation: 1768
I have some forms which are creating dynamically and I have a common submit button, on that click, I need to loop through all forms and get the value of one particular element and need to get the sum. I have given some sample code below, the problem is, the code is executing 4 times, but Im expecting the loop should execute 2 times. what is wrong with this code ?
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$("document").ready(function() {
$('form').each(function(index) {
$('form > select').each(function(selindex) {
alert(index + ":"+ selindex + ': ' + $(this).text());
});
});
});
</script>
</head>
<body>
<form name="form[1]">
<input type="text">
<select name="select[1]">
<option value="1">One 1</option>
<option value="2">Two 1</option>
</select>
</form>
<form name="form[2]">
<select name="select[2]">
<option value="1">One 2</option>
<option value="2">Two 2</option>
</select>
</form>
</body>
</html>
Upvotes: 1
Views: 3281
Reputation: 93003
Remove the outer loop -- your inner selector is enough to get data from all forms in the document:
$('form > select').each(function(selindex) {
alert(index + ":"+ selindex + ': ' + $(this).text());
});
Upvotes: 4