【问题标题】:Checkbox not returning the right value jquery/php复选框未返回正确的值 jquery/php
【发布时间】:2018-06-14 13:07:36
【问题描述】:

我正在尝试获取复选框的值(真或假)并在 while 函数中更新一行的数据库。但是,复选框似乎只根据第一行记录值的变化。例如,如果选中第 1 行复选框,则 value = true。然后我可以单击以下行并获取 true 的复选框值。但是,当我单击第一行之外的行以获得错误时,它只会在第一行复选框未选中的情况下注册。我认为这与行 ID 有关,但尝试了很长时间来修复它但无法修复它。请帮忙。

HTML/PHP

while($row = $result->fetch_assoc()) {

echo
'
<input type="checkbox" name="home['.$row["id"].']" id="'.$row["id"].'" '.($row["home"]>0 ? 'checked="checked"' : '').'>
            <label for="'. $row["id"].'"></label>

JQUERY

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

PHP/MYSQL

  if ($home == 'true') {
  $check = date("Ymd");
} else {
  $check = '';
}
if(isset($_POST["home"])) {
  $sql = "UPDATE addresses SET home='$check' WHERE id='$id'";
  if($mysqli->query($sql) === TRUE){
         } else {
      echo "error" . $sql . "<br>".$mysqli->error;
    }
  }

【问题讨论】:

    标签: php jquery html mysql


    【解决方案1】:

    问题是因为您选择了点击处理程序中的所有复选框,然后访问该集合上的prop(),这只会返回第一个的值。

    改为使用this 关键字来引用引发事件的复选框。出于可访问性原因,您还应该使用change 事件而不是click

    $('input[type="checkbox"]').on('change', function(){
      var on = $(this).prop("checked"); // or just this.checked
      $.post("work/updateaddress.php", {
        home: on,
        id: this.id
      });
    });
    

    【讨论】:

    • 没问题。如果有帮助,请不要忘记接受答案 - 也包括您之前的一些问题。
    【解决方案2】:

    //使用this来引用被点击的框:

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

    【讨论】:

      【解决方案3】:

      您应该为复选框使用change 事件而不是click 事件。

      $('input[type="checkbox"]').on('change', function(){
        var on = this.checked
        console.log(on)
      });
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <input type="checkbox" value="a">

      【讨论】:

        【解决方案4】:

        或者改变你可以使用input

        $('input[type="checkbox"]').on('input', function(e){
          let thisCheckbox = e.target.checked
          alert(thisCheckbox)
        });
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <input type="checkbox" name="row1" id="row1" checked="checked">
                    <label for="row1">row1</label>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-12-13
          • 1970-01-01
          • 2016-03-06
          • 1970-01-01
          • 2016-05-03
          • 2022-12-15
          相关资源
          最近更新 更多