Beldion Bryan Balanan Beldion Bryan Balanan - 1 year ago 77
jQuery Question

alert on check selector jQuery

Please advise on why the alert is not working, I have tried several methods and it still wont alert when the checkbox is being checked.



$(document).ready(function(){
$('.classname').on('change', function(){
if(this.checked)
{
alert("hello world");
}
});
});

$(document).ready(function() {
$('.classname').change(function() {
if ($(this).prop('checked')) {
alert("hello World");
}

});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="checkbox" id="classname"> 1st method

<input type="checkbox" id="classname2"> 2nt method





Can anyone please tell me where I went wrong or what I missed?

Answer Source

Your error is pretty simple. You used the class selector instead of the id selector.

Make sure that you add the same class to both the checkboxes for it to function correctly.

$(document).ready(function(){
  $('.classname').on('change', function(){ 
    if(this.checked) 
    {
    alert("hello world");
    }
  });
});

$(document).ready(function() {
  $('.classname').change(function() {
    if ($(this).prop('checked')) {
        alert("hello World"); 
    }

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="checkbox" class="classname"> 1st method

<input type="checkbox" class="classname"> 2nt method