0

I have multiple checkboxes in a for each loop all with different data attributes.

  <input data-pid="<?php echo $name ?>" class="live" name="live" id="live" type="checkbox" value="">

In JQuery I am trying to fetch the data attribute of the checked option and whether it is checked or not.

   $(".live").click(function() {

    var n = this.id
    var a = this.attr("data-pid");

I don't seem to be able to get the id or attr

3
  • in your function you can do this.checked to see if it is checked or not Commented May 10, 2017 at 21:33
  • how about the data attribute Commented May 10, 2017 at 21:38
  • change var a = this.attr("data-pid"); to var a = $(this).attr("data-pid"); Commented May 11, 2017 at 15:40

2 Answers 2

1

https://jsfiddle.net/nydo9ues/1/

$('.live').change(function(){
var chkbx=$(this);
console.log(chkbx.data());//Will give you a JSON Object with your data https://api.jquery.com/data/
console.log(chkbx.attr('id'));//id of the element changing
console.log(chkbx.is(':checked'));//Status of the checkbox


});
Sign up to request clarification or add additional context in comments.

Comments

0

attr() is a jQuery method so you have to use $(this).attr() not this.attr()

$(function() {
   $(".live").change(function() {
     var n = this.id
     var a = $(this).attr("data-pid");
     console.log('id=', n, ' pid=', a , ' checked=', this.checked)
   });
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" data-pid="1" id="live_1" class="live">
<input type="checkbox" data-pid="2" id="live_2" class="live">
<input type="checkbox" data-pid="3" id="live_3" class="live">
<input type="checkbox" data-pid="4" id="live_4" class="live">
<input type="checkbox" data-pid="5" id="live_5" class="live">

Use your console to check for errors. You should have seen one for this.attr() is not a function

Comments

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.