如何通过同一标签下的复选框值获取隐藏值

时间:2016-10-20 12:10:41

标签: javascript jquery html selector

我有一张这样的表:

<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());
});

当然,在我得到我想要的价值后,我会将它保存到数组中。

3 个答案:

答案 0 :(得分:1)

试试这个:

$("input[type='checkbox']").each( function (){
    var value = $(this).parent().find("input:hidden").val();
    // this will return the value of each hidden field
});

答案 1 :(得分:1)

不确定为什么值不在复选框上,它会简化代码。

但是使用您的代码,您只需使用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>

答案 2 :(得分:0)

您可以使用兄弟姐妹和输入类型隐藏来获取值。

$("#TempTable tr input[type=checkbox]:checked").each(function(){
   $(this).siblings('input[type=hidden]').val()
});
相关问题