单选按钮选中和取消选中 onclick 并发送数据

Radio button check and uncheck onclick and send data

我正在尝试使用单选按钮通过 ajax 发送数据 onclick。如果单击并选中单选按钮,则在数据库中设置值 1。如果已选中单选按钮,但单击取消选中它,则将 0 值发送到数据库。我正在使用的代码发送值 onclick 并检查单选按钮,但不会取消选中,因此不会将值发送到数据库。请帮忙。

<input type="radio" name="home['. $row["id"].']" id="'. $row["id"].'">

<script>
$(document).ready(function(){
    $('input[type="radio"]').click(function(){

        var checked = $(this).prop('checked');

        if (checked != 'checked') {
            $(this).prop('checked', true);
            var id = $(this).attr('id');
            $.ajax({
                 url:"updateaddress.php",
                 method:"POST",
                 data:{home:"1",id:id,},
            });
        } else if (checked == 'checked') {
            $(this).prop('checked', false);
            var id = $(this).attr('id');
            $.ajax({
                 url:"updateaddress.php",
                 method:"POST",
                 data:{home:"0",id:id,},
        });

        }
    });                           
});
</script>

当有多个选项时使用单选按钮,用户应该只选中一个 option.so,当已经 checked.you 显式创建 onclick 侦听器并更改单选按钮时,用户不能取消选中单选按钮按钮 status.but 它不是 advisable.you 可以将复选框用于 onchange 事件。

$(checkEle).on("change",function(){
  var status = $(this).prop("checked");
  sendStatus(status);
}
<input type="radio" name="home['. $row["id"].']" id="'. $row["id"].'">

<script>
$(document).ready(function(){
    $('input[type="radio"]').click(function(){
        var data = {home:"0",id:$(this).attr("id")};
        if ($(this).is(":checked")) {
            data = {home:"1",id:$(this).attr("id")};
        }
         $.ajax({
                 url:"updateaddress.php",
                 method:"POST",
                 data:data,
         });

    });                           
});
</script>

您可以使用此 script.Just 检查单选按钮是否被选中,并相应地发送您的值。

一个复选框和

$('input[type="checkbox"]').on("click", function(){ 
  $.post("updateaddress.php",{home:this.checked,id:this.id});
}); 

就是你所需要的

如果你必须使用收音机,看看这个

$('input[type="radio"]').on("click", function(){ 
  $.post("updateaddress.php",{home:this.checked,id:this.id});
  this.checked=!this.checked;
});