代码之家  ›  专栏  ›  技术社区  ›  oshirowanen

jquery ajax复选框状态

  •  11
  • oshirowanen  · 技术社区  · 14 年前

    我的页面上有复选框,我想通过Ajax将它们的状态发送回数据库。我知道如何在Ajax中使用jquery,但是我不知道如何获取选中状态,包括选中和未选中状态以及复选框的ID,这样我就可以将其发送回服务器。

    有什么想法吗?

    5 回复  |  直到 9 年前
        1
  •  20
  •   Ain Tohvri    14 年前
    if ($("#yourCheckboxID").is(":checked")) {  
        // checkbox is checked 
    } else {
        // checkbox is not checked 
    }
    

        2
  •  16
  •   oshirowanen    14 年前

    <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
  •  9
  •   chridam Gino Claudi    12 年前

    <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
  •  2
  •   stuart    9 年前

    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
  •  0
  •   Pointy    14 年前

    $(':checkbox').whatever()
    

    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

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

    $.ajax