jQuery Ajax checkbox state

后端 未结 5 514
耶瑟儿~
耶瑟儿~ 2021-02-04 11:33

I have checkboxes on my page for which I would like to send their state back to the database via ajax. I know how to use jquery with ajax, but I don\'t know how to get the chec

5条回答
  •  后悔当初
    2021-02-04 12:21

    Well it's easy enough to find the checkboxes:

    $(':checkbox').whatever()
    

    The trick is that in HTML checkboxes only have a value that's meaningful when checked. When they're not checked, what do you tell the server?

    Well if you've got a convention to work with (perhaps always sending "true" when checked and "false" when not checked), the next thing you have to decide is how to get them to your server. You can use the jQuery param function to turn the list into a parameter string:

    var params = $.param($(':checkbox').map(function() {
       return { name: this.id, value: !!this.checked };
    }));
    

    That gives you a string ready to be tacked onto a URL, or sent as data via $.ajax.

提交回复
热议问题