简体   繁体   English

如何使用jQuery在循环中获取选中的复选框值?

[英]How to get selected checkbox value in a loop using jQuery?

I have a PHP while loop where I insert the following code to show On and Off button. 我有一个PHP while循环,我插入以下代码来显示On和Off按钮。

<div class="onoffswitch">
    <input type="hidden" name="hiddenID" value="<?php echo $id; ?>">
    <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch<?php echo $i ?>" <?php echo $status; ?>>
    <label class="onoffswitch-label" for="myonoffswitch<?php echo $i; ?>">
        <span class="onoffswitch-inner"></span>
        <span class="onoffswitch-switch"></span>
    </label>
</div>

Now I want to get hidden ( hiddenID ) field value when the on-off button is changed but it's showing me undefined with following code: 现在我想在开关按钮被更改时获取隐藏hiddenID )字段值,但它显示未定义以下代码:

$(document).ready(function () {
    $(".onoffswitch").change(function() {
      var hiddenID = $(this).attr('hiddenID');      
      alert(hiddenID);
    });
});

Why it's showing me undefined error? 为什么它会向我显示未定义的错误?

$(this) you are, at present, in the onoffswitch check box. $(this)您目前在onoffswitch复选框中。 It doesn't have an attribute hiddenID 它没有属性hiddenID

also the hiddenID is not an attribute in it's parent element. hiddenID也不是其父元素中的属性。 It is a value of the name attribute. 它是name属性的值。

use $(this).prev().val() 使用$(this).prev().val()

or 要么

$(document).ready(function () {
    $(".onoffswitch").change(function() {
      var hiddenID = $(this).prev("[name=hiddenID]").val()
      alert(hiddenID);
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM