简体   繁体   中英

change event using name attribute of checkbox JS

I have this multiple checkboxes with same name attribute: myTask

<input type="checkbox" class="sol-checkbox" name="myTask" value="1B">
<input type="checkbox" class="sol-checkbox" name="myTask" value="2B">
<input type="checkbox" class="sol-checkbox" name="myTask" value="3B">

and

I have this jQuery code to perform every time the user clicks on the checkboxes

$("input[name='myTask'").change(function(){
   alert(1);
});

is there anything wrong with my script?

Please check may be something wrong in your code. You have forgot to add one square bracket

 $("input[name='myTask']").change(function(){ alert($(this).val()); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="checkbox" class="sol-checkbox" name="myTask" value="1B"> <input type="checkbox" class="sol-checkbox" name="myTask" value="2B"> <input type="checkbox" class="sol-checkbox" name="myTask" value="3B">

You forgot add one closing square bracket.

Please try below code.

Way to trigger the on change through the input type.

// Shorthand for $( document ).ready()
$(function() {
    console.log( "ready!" );
    $("input[name='myTask']").change(function(){
        alert($(this).val());
    });
});

Way to trigger the on change through the class name of the input field.

// Shorthand for $( document ).ready()
$(function() {
    console.log( "ready!" );
    $(".sol-checkbox").change(function(){
        alert($(this).val());
    });
});

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