jQuery Ajax checkbox state

こ雲淡風輕ζ 提交于 2019-12-03 09:24:51

问题


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 checked state, both checked and unchecked along with the id of the checkbox so I can send it back to the server.

Any ideas?


回答1:


if ($("#yourCheckboxID").is(":checked")) {  
    // checkbox is checked 
} else {
    // checkbox is not checked 
}

will do the job.




回答2:


Something like this:

<script type="text/javascript">
    $(document).ready(function(){
        $("input:checkbox").change(function() { 
            if($(this).is(":checked")) { 
                $.ajax({
                    url: 'on_off.aspx',
                    type: 'POST',
                    data: { strID:$(this).attr("id"), strState:"1" }
                });
            } else {
                $.ajax({
                    url: 'on_off.aspx',
                    type: 'POST',
                    data: { strID:$(this).attr("id"), strState:"0" }
                });
            }
        }); 
    });
</script>



回答3:


Combining your solution and the accepted answer by Ain:

<script type="text/javascript">
  $(document).ready(function(){
    var isChecked = $("input:checkbox").is(":checked") ? 1:0; 
    $.ajax({
            url: 'on_off.aspx',
            type: 'POST',
            data: { strID:$("input:checkbox").attr("id"), strState:isChecked }
    });        
  });
</script>



回答4:


Adding back in the change event to the merged solution. Want this to fire every time checkbox is changed.

<script type="text/javascript">
    $(document).ready(function(){
        $("input:checkbox").change(function() { 
            var isChecked = $("input:checkbox").is(":checked") ? 1:0; 
            $.ajax({
                url: 'on_off.aspx',
                type: 'POST',
                data: { strID:$("input:checkbox").attr("id"), strState:isChecked }
            });        
        });        
    });
</script>



回答5:


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.



来源:https://stackoverflow.com/questions/3117673/jquery-ajax-checkbox-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!