2

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?

1
  • you should be listening for input, not div - $('[name="hiddenID"]') Commented Jun 24, 2017 at 11:34

1 Answer 1

1

$(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);
    });
});
Sign up to request clarification or add additional context in comments.

8 Comments

Well, it's removed the error message but get the same id value every time. is there anything am I missing?
I think you are calling it in the wrong place. Try the code block
and this line $(this).prev().val(); showing unefined error message and your updated is showing me same id value.
are you changing the value each time when the checkbox is toggled using ajax?
The code I have posted is in the php while loop. Here I am using hidden input field to show the id value which is different. Now I want to alert this hidden id value when checkbox is changed
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.