在jQuery表中的选择框中循环

Iterating through select boxes in a table jQuery

本文关键字:循环 选择 jQuery      更新时间:2024-03-17

我的表单中有添加行选项,用户可以添加任意多的行,然后通过ajax一次提交所有行。

每一行都包含选择框和一堆文本框。

文本框是正确提交的,但我的表单只提交了所有其他行的第一行中的选择框值,尽管值不同。

在正确解释了我的问题后(hoepfully),这里是选择框的html代码的代码:

<td><span id="xyz"><select id="whatever">
<option value="one">ONE</option>
 <option value="two">TWO</option>
<option value="three">THREE</option>
</select>
</span></td>

下面是jQuery获取所有选择框值的不同代码版本的代码:

$("#table tbody tr").each(function(){
var select = $(this).find("td:eq(0)").find("select#whatever).val();
//etc
}

$("#table tbody tr").each(function(){
var select = $("select#whatever).val();
//etc
}

$("#table tbody tr").each(function(){
var select = $(this).find("td:eq(0)").find("select#whatever option:selected").val();
//etc
}

$("#table tbody tr").each(function(){
var select = $(this).find("td:eq(0)").find("select#whatever").val();
//etc
}

$("#table tbody tr").each(function(){
var select = $(this).find("td:eq(0)").find("select").val();
//etc
}

$("#table tbody tr").each(function(){
var select = $(this).find("td:eq(0).xyz").find("select#whatever").val();
//etc
}

$("#table tbody tr").each(function(){
var select = $(this).find("td:eq(0).dropdown select#whatever").val();
//etc
}

$("#table tbody tr").each(function(){
var select = $(this).find("td:eq(0)").find("select#whatever").val();
//etc
}

$("#table tbody tr").each(function(){
var select = $("select#whatever option:selected").val();
//etc
}

$("#table tbody tr").each(function(){
var select = $("select option:selected").val();
//etc
}

以上是各种版本的代码,如果我没记错的话,我已经在IE 8中尝试过了,但没有太大成功。

它们在IE 9和firefox等其他浏览器中运行良好。

循环运行良好,因为我可以获得其他输入框的值。

我也尝试过没有id属性的html select boxe,但也不起作用。

我真的需要别人的帮助。

提前感谢天才。

马克。

我想你正在寻找这个:

var selectValue = $(this).find("td:eq(0)").find("select option:selected").val();

假设每行只有一个选择框,这应该有效:

var values = $("#table select").map(function(){
    return $(this).val();
}).get();

如果您有更复杂的标记,并且只想从每行的第一个单元格中获取值,则可以将选择器更改为

$('#table td:first-child select')