简体   繁体   中英

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.

<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:

$(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. It doesn't have an attribute hiddenID

also the hiddenID is not an attribute in it's parent element. It is a value of the name attribute.

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

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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