jQuery Ajax复选框状态

osh*_*nen 11 ajax checkbox jquery state

我的页面上有复选框,我想通过ajax将状态发送回数据库.我知道如何使用jquery与ajax,但我不知道如何获得已检查状态,检查和取消选中以及复选框的ID,以便我可以将其发送回服务器.

有任何想法吗?

Ain*_*vri 22

if ($("#yourCheckboxID").is(":checked")) {  
    // checkbox is checked 
} else {
    // checkbox is not checked 
}
Run Code Online (Sandbox Code Playgroud)

会做的.


osh*_*nen 16

像这样的东西:

<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>
Run Code Online (Sandbox Code Playgroud)


chr*_*dam 9

结合您的解决方案和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>
Run Code Online (Sandbox Code Playgroud)