【问题标题】:How to change the checkbox property如何更改复选框属性
【发布时间】:2019-09-26 03:56:33
【问题描述】:

在数据库中的表中包含列日期、复选框。如果输入的日期已经在数据库中,如何禁用复选框。例如,如果表中包含日期 = 13/9/2019 和复选框 = h1,那么如果我们输入日期 13/9/2019,复选框h1 被禁用,反之亦然

$(document).ready(function {
  $("#date").change(function {
    var date = $("#date").val();

    $.ajax({
      url: "variable.php",
      method: "POST",
      data: {
        date2: date
      },
      dataType: "text",
      success: function(html) {
        //what to put here?
      }
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date" id="date">
<input type="checkbox" name="checkbox[]" id="checkbox" name="h1">
<input type="checkbox" name="checkbox[]" id="checkbox" name="h2"">
<?php  $db = mysqli_connect('localhost','root','','mydatabase');
if (isset($_POST['date2'])){
$query = mysqli_query($db, "SELECT * FROM mytable where date = 
 '".$_POST["date2"]."'");
// what to put here?
}
?>

【问题讨论】:

    标签: php jquery ajax mysqli


    【解决方案1】:

    首先,您的 PHP 脚本需要改进。您应该启用error reporting 并使用准备好的语句。该值还应在使用前进行验证。

    <?php
    
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $db = new mysqli('localhost','root','','mydatabase');
    $db->set_charset('utf8mb4');
    
    if (isset($_POST['date2'])) {
        $date = (new DateTime($_POST["date2"]))->format('Y-m-d'); //validate format
        // prepare -> bind -> execute
        $stmt = $query = $db->prepare("SELECT 1 FROM mytable WHERE date = ? ");
        $stmt->bind_param('s', $date);
        $stmt->execute();
        // get a single column from the first row of the mysql result
        $exists = (bool)$stmt->get_result()->fetch_row();
    
        // send JSON response to AJAX
        echo json_encode(['exists' => $exists]);
    }
    

    然后在你的 AJAX 中你需要检查返回的值。

    $(document).ready(function {
      $("#date").change(function {
        var date = $("#date").val();
    
        $.ajax({
          url: "variable.php",
          method: "POST",
          data: {
            date2: date
          },
          dataType: "text",
          success: function(response) {
            $obj = JSON.parse(response); // Since the datatype is text we need to make in a valid JSON
            $("#checkbox_h1").attr("disabled", $obj.exists); // $obj.exists has the return value from mysql
          }
        });
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="date" id="date">
    <input type="checkbox" name="checkbox[]" id="checkbox_h1" name="h1">
    <input type="checkbox" name="checkbox[]" id="checkbox_h2" name="h2"">

    这是一个非常粗略的代码,仅供您参考。你可以写类似的东西。

    【讨论】:

    • fetch_row()[0] 如果没有找到记录,快捷方式将导致未定义索引错误。它应该是我在查询中编辑代码或 count(1) 的方式。 PDO 更好的另一个原因 - 没有这样的怪癖:)
    • @YourCommonSense 我测试了它(PHP 7.2.5),但我不能看到错误消息。我一定做错了什么。不过,您提议的方式似乎更好。
    • 看,当没有找到结果时,fetch_row() 返回 false。并尝试从 false 访问数组元素将 produce an error
    • @YourCommonSense 我明白了,所以它只在 PHP 7.4 中添加。 wiki.php.net/rfc/notice-for-non-valid-array-container
    • 哦,废话。我不知道这种行为,甚至忽略了我自己的例子。我很抱歉。
    【解决方案2】:

    在你的 php 文件中放。

     <?php  $db = mysqli_connect('localhost','root','','mydatabase');
     if (isset($_POST['date2'])){
     $result = mysqli_query($db, "SELECT * FROM mytable where date = 
      '".$_POST["date2"]."'");
       if ($result) 
       { 
         // it return number of rows in the table. 
         $row = mysqli_num_rows($result); 
    
         if($row > 0){
              echo 1; //exist
         } else {
              echo 0; // not exist
         // close the result. 
         mysqli_free_result($result); 
       } 
     }
     ?>
    

    在 ajax 中

    $.ajax({
      url: "variable.php",
      method: "POST",
      data: {
        date2: date
      },
      dataType: "text",
      success: function(html) {
        if(html == 1){
            // hide checkbox
            $(".checkboxClass").attr("disabled","disabled");
        }
      }
    });
    

    【讨论】:

      【解决方案3】:

      你应该在 ajax 成功回调中返回 true|false 并将下面的代码放在成功回调中

      $.ajax({
        url: "variable.php",
        method: "POST",
        data: {
          date2: date
        },
        dataType: "text",
        success: function(result) {
         if(result == true || result == 'true'){ // # just to be safe side
             $("input[type='checkbox']").attr("disabled",true); // #disable the checkbox
          }
        }
      });
      

      【讨论】:

      • 我已经编辑了我的问题,因为它应该是复选框数组
      【解决方案4】:

      在mysqli_query之后做这样的事情

      if (isset($_POST['date2'])){
          $query = mysqli_query($db, "SELECT * FROM mytable where date = '".$_POST["date2"]."'");
          if (mysqli_num_rows($query) > 0)
          {
              // print/echo or return(if a return-function) - true/1/successful
              // eg.
              print 1;
              exit();
          }
      }
      

      并在 Ajax 响应中得到结果

      $.ajax({
        url: "variable.php",
        method: "POST",
        data: {
          date2: date
        },
        dataType: "text",
        success: function(html) {
          //what to put here?
          if (html == 1) {
              //disable checkbox
          }
        }
      });
      

      【讨论】:

      • ajax 的成功:ajax 的函数呢?
      • Ajax 成功将返回响应。在您的情况下,它是html。您可以使用 console.log 来检查响应
      【解决方案5】:
      <?php  
      $db = mysqli_connect('localhost','root','','mydatabase');
      if (isset($_POST['date2'])){
          $query = mysqli_query($db, "SELECT * FROM mytable where date = 
                 '".$_POST["date2"]."'");
          // what to put here?
          retunr mysqli_num_rows($query);
      }
      ?>
      

      首先返回行数。如果行数大于0,则表示该日期存在于数据库中。 在前端选中此项,如果大于 0,则禁用该复选框。

      $(document).ready(function {
        $("#date").change(function {
          var date = $("#date").val();
      
          $.ajax({
            url: "variable.php",
            method: "POST",
            data: {
              date2: date
            },
            dataType: "text",
            success: function(html) {
              if(html > 0){
                $('#checkbox').attr("disabled", true);
              }
            }
          });
        });
      });
      

      【讨论】:

      • 如果我有很多复选框,我如何指定禁用哪个复选框?
      猜你喜欢
      • 2014-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-08
      相关资源
      最近更新 更多