复选框选中事件和提交按钮

checkboxes selected event and submit button

本文关键字:提交 按钮 事件 复选框      更新时间:2023-09-26

我刚刚完成了使用ajax的多个复选框的小项目。演示可以在这里找到:demo。但现在我想使用提交按钮的过滤器选项。所以现在在多个复选框被选中之后,在sumbit按钮被点击之后,只有它应该在电话数据库中改变。有什么帮助吗?谢谢。这是我的代码:index . php

<body> 
    <h1>Phones database</h1>
    <table id="phones">
      <thead>
        <tr>
          <th>ID</th>
          <th>Brand</th>
          <th>Model</th>
          <th>Price</th>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>
    <div id="filter">
      <h2>Filter options</h2>
      <div>
        <input type="checkbox" id="Samsung" checked>
        <label for="Samsung">Samsung</label>
      </div>
      <div>
        <input type="checkbox" id="iPhone" checked>
        <label for="iPhone">iPhone</label>
      </div>
      <div>
        <input type="checkbox" id="HTC" checked>
        <label for="HTC">HTC</label>
      </div>
      <div>
        <input type="checkbox" id="LG" checked>
        <label for="LG">LG</label>
      </div>
      <div>
        <input type="checkbox" id="Nokia" checked>
        <label for="Nokia">Nokia</label>
      </div>
    </div>
    <script src="http://code.jquery.com/jquery-latest.js"></script> 
    <script>
      function makeTable(data){
        console.log(data);
       var tbl_body = "";
          $.each(data, function() {
            var tbl_row = "";
            $.each(this, function(k , v) {
              tbl_row += "<td>"+v+"</td>";
            })
            tbl_body += "<tr>"+tbl_row+"</tr>";
          })
        return tbl_body;
      }
      function getPhoneFilterOptions(){
        var opts = [];
        $checkboxes.each(function(){
          if(this.checked){
            opts.push(this.id);
          }
        });
        return opts;
      }
      function updatePhones(opts){
        $.ajax({
          type: "POST",
          url: "submit.php",
          dataType : 'json',
          cache: false,
          data: {filterOpts: opts},
          success: function(records){
            $('#phones tbody').html(makeTable(records));
          }
        });
      }
      var $checkboxes = $("input:checkbox");
      $checkboxes.on("change", function(){
        var opts = getPhoneFilterOptions();
        updatePhones(opts);
      });
      $checkboxes.trigger("change");
    </script> 
  </body> 
</html>

submit.php

<?php 
require 'Database.php';
#### TEMP SET NAMES FÜR UTF8 ###################################################
include 'Json.php';
  $opts = $_POST['filterOpts'];
  $tmp = array();
  foreach ($opts as $opt) {
        $tmp[] = '"'.$opt.'"';
  }
        $query = 
      'SELECT mobile_phone.id, name, model, price FROM mobile_phone INNER JOIN brand ON brand_id = brand.id WHERE name IN ('.implode(",", $tmp).')';

  $result = mysql_query($query);
  $data   = array();
  while ($row = mysql_fetch_assoc($result)) {
  $data[] = $row;
  }
echo json_encode($data);
?>

这一行data: {filterOpts: opts},改为

data: {filterOpts: $(':checked').val('id')}

这应该传递模型的id