简体   繁体   中英

Getting the value of the checkbox value that has been changed

I have several checkboxes on my page that each correspond to different courses. When the user checks the checkbox I want to sent a POST request to the server to add details of their enrollment to the database.

I have the following jQuery to take note of the change:

$(function () {
    $("input:checkbox").change(function () {
        var fullURL = document.URL;
        var url = fullURL.split('userID=');
        var userID = url[1];

        var courseID =

        alert(userID + "and " + courseID);

        $.post('/Admin/EnrolUser/', postData, function (data) {

        });
    });
});

On my page there are several checkbox inputs, how can I retrieve the value of the selected checkbox that fired the event and set this to the var courseID variable.

Every jQuery function that deals with collections set's the value of this to be the current element.

So...

$("input:checkbox").on("change", function(){

   $(this).val(); //Element that fired event

});

Inside your change function the variable this represents your checkbox.

    $("input:checkbox").change(function () {
    var fullURL = document.URL;


    var courseID = $(this).val();

    alert(courseID);

});

jsfiddle here

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