JQuery gets correct value based on checkbox

I cannot get this simple code to work. I want to get the value from the data attribute and based on this pass it to alert

http://jsfiddle.net/btL9C/

$("input[type=checkbox]").change(function() {
     var section_list = $('.section').data('section_list');

     if ($(this).hasClass(section_list+"_list")) {          
         alert(section_list);
     }
});

HTML:

<input type="checkbox" data-section_list = "1" class="section 1_list">
<input type="checkbox" data-section_list = "2" class="section 2_list">
<input type="checkbox" data-section_list = "3" class="section 3_list">

How can I get a warning to display the corresponding value for the data-section_list section?

+4
source share
7 answers

try it

$("input[type=checkbox]").change(function() {

    var section_list = $(this).data().section_list;

   if ($(this).hasClass(section_list+"_list")) {          
        alert(section_list);
   }
});
+4
source

Try using the link $(this)when extracting datafrom the current item,

$("input[type=checkbox]").change(function () {
    var section_list = $(this).data('section_list');
    if ($(this).hasClass(section_list + "_list")) {
        alert(section_list);
    }
}); //-- You have missed to mention the close parenthesis here.

Demo

+2
source

  • - change.
  • $(this) .

$(document).ready(function(){
    $("input[type=checkbox]").change(function() {
         var section_list = $(this).data('section_list');

         if ($(this).hasClass(section_list+"_list")) {          
             alert(section_list);
         }
    });  // <-- Missing
});
+2

clicked this, $(".section"), , :

:

var section_list = $(".section").data('section_list');

var section_list = $(this).data('section_list'); //<--- gets current cliked element data attribute

:

$("input:checkbox").change(function() {
     var section_list = $(this).data('section_list');

     if ($(this).hasClass(section_list+"_list")) {          
         alert(section_list);
     }
});

FIDDLE

+2

,

$("input[type=checkbox]").change(function() {
     var section_list = $(this).attr('data-section_list');

     if ($(this).hasClass(section_list+"_list")) {          
         alert(section_list);
     }
}
+1

: .section

<script type="text/javascript">
$(document).ready(function() {

$("input[type=checkbox]").change(function() {
     var section_list = $(this).data('section_list');

     if ($(this).hasClass(section_list+"_list")) {          
         alert(section_list);  
     }
});  
});  
</script> 

http://jsfiddle.net/btL9C/3/

+1

: -

$("input[type=checkbox]").click( function(){
   if( $(this).is(':checked') ) alert($(this).attr("data-section_list"));
});
+1

Source: https://habr.com/ru/post/1545618/


All Articles