我有一个这样的表:
<table id="TempTable">
<tr>
<td>
<input type="checkbox" id="chkbox1"/>
<input type="hidden" value="1" />
</td>
</tr>
<tr>
<td>
<input type="checkbox" id="chkbox2"/>
<input type="hidden" value="2" />
</td>
</tr>
<tr>
<td>
<input type="checkbox" id="chkbox3"/>
<input type="hidden" value="3" />
</td>
</tr>
</table>
我想在与选中的复选框相同的 td
中获取隐藏值。
我尝试过这个:
$("#TempTable tr input:checkbox:checked").each(function(){
alert($("#"+this.id).parent("td").child("input:hidden").val());
});
当然,当我获得我想要的值后,我会将其保存到数组中。
最佳答案
不确定为什么这些值不在复选框上,这会简化代码。
但是对于您的代码,您只需使用 next 和 map 即可。
$(":checkbox").on("change", function() {
var vals = $(":checkbox:checked").map( function(){
return $(this).next().val();
}).get();
console.log(vals);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="TempTable">
<tr>
<td>
<input type="checkbox" id="chkbox1"/>
<input type="hidden" value="1" />
</td>
</tr>
<tr>
<td>
<input type="checkbox" id="chkbox2"/>
<input type="hidden" value="2" />
</td>
</tr>
<tr>
<td>
<input type="checkbox" id="chkbox3"/>
<input type="hidden" value="3" />
</td>
</tr>
</table>
正如我在将值放在复选框上之前所说的那样,简化了它
$(":checkbox").on("change", function() {
var vals = $(":checkbox:checked").map( function(){
return this.value;
}).get();
console.log(vals);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="TempTable">
<tr>
<td>
<input type="checkbox" id="chkbox1" value="1"/>
</td>
</tr>
<tr>
<td>
<input type="checkbox" id="chkbox2" value="2"/>
</td>
</tr>
<tr>
<td>
<input type="checkbox" id="chkbox3" value="3"/>
</td>
</tr>
</table>
关于javascript - 如何从同一 <td> 标记下通过复选框值获取隐藏值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40154056/