【问题标题】:How can I retain checkboxes checked state after page submit and reload?页面提交和重新加载后如何保留复选框选中状态?
【发布时间】:2017-12-30 16:05:51
【问题描述】:

我有一个名为property_amenities 的表,它有列; amenity_idamenity_name 的值在表单上填充为复选框。提交表单后,检查的值将作为数组插入到 property_amenities 列上的 property_listings 表中。

    <?php
      $db_host="localhost";
      $db_name="cl43-realv3";
      $db_user="root";
      $db_pass="";

        try
        {
          $DB_con = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
          $DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $e)
        {
          $e->getMessage();
        }

        if (isset($_POST['list_property'])) {
          if (isset($_POST['property_amenities'])) { 
            $property_amenities = implode(",",$_POST['property_amenities']);
          }else{ $property_amenities = "";}
        }
     ?>
      <!DOCTYPE html>
      <html>
      <head>
        <title></title>
      </head>
      <body>
          <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
         <div class="row clearfix">
          <div class="col-lg-12 col-md-6 col-sm-12">  
        <?php
          $stm = $DB_con->prepare("SELECT * FROM property_amenities");
          $stm->execute(array(
          ));

          while ($row = $stm->fetch()){
            $amenity_id = $row['amenity_id'];
            $amenity_name = $row['amenity_name']; 
            $List[] ="<label class=checkbox> <input type=checkbox name='property_amenities[]' value='$amenity_name'> $amenity_name</label>";
          }
          $allamenities = $stm->rowCount();

          $how_many_chunks = $allamenities/3;

          $roster_chunks = array_chunk($List, round($how_many_chunks), true);
          ?>

            <label>Property Amenities</label></small>

        <?php
          foreach ($roster_chunks as $roster_chunk_key => $roster_chunk_value) {
            echo "<div class='col-lg-3 col-md-6 col-sm-12'>";
            echo join($roster_chunk_value);
            echo '</div>';
          }
        ?>                                

          </div> 
         </div><!-- end row -->
        <button type="submit" class="btn btn-primary" name="list_property" >SUBMIT PROPERTY</button>
        </form>
    </body>
    </html>

上面的代码工作正常。唯一的问题是,当我提交表单并且页面重新加载时,property_amenities 的所有复选框都未选中,我想要的是在页面提交之前选中的复选框被选中。

我怎样才能做到这一点?

这是 property_amenities 表

--
-- Table structure for table `property_amenities`
--

CREATE TABLE `property_amenities` (
  `amenity_id` int(11) NOT NULL,
  `amenity_name` varchar(60) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `property_amenities`
--

INSERT INTO `property_amenities` (`amenity_id`, `amenity_name`) VALUES
(1, 'Outdoor Balcony'),
(2, 'Outdoor Yard Access'),
(3, 'Large Windows/Natural Light'),
(4, 'Closet Space'),
(5, 'Storage Space'),
(6, 'Laundry in Unit'),
(7, 'Parking Garage'),
(8, 'Ample Parking'),
(9, 'Stainless Steel Appliances'),
(10, 'Open Floor Plan'),
(11, 'Newly Renovated'),
(12, 'Close to Social Amenities'),
(13, 'Swimming Pool'),
(14, 'Courtyard'),
(15, 'Electric Fence'),
(16, 'Intercom'),
(17, 'Patio'),
(18, 'Internet'),
(19, 'Guest Quarters'),
(20, 'Gym / Workout Room'),
(21, 'Kitchenette'),
(22, 'Day And Night Guards'),
(23, 'Borehole'),
(24, 'Street Lights'),
(25, '3 Phase Power'),
(26, 'Dhobi Area'),
(27, 'Wheelchair Access '),
(28, 'Generator');

【问题讨论】:

    标签: php mysql


    【解决方案1】:

    只需在您的数据库中检查哪些复选框已被选中,并将 checked 属性包含在您回显复选框时的那些复选框中:

    $checked = (condition) ? "checked" : "";
    
    $List[] = "<label class=checkbox>
                  <input type=checkbox name='...' value='$amenity_name' $checked/>
                  $amenity_name
               </label>";
    

    编辑:

    (回复comment

    由于每个checkboxvalue 是便利设施的名称,您可以使用提交表单时获得的$_POST['property_amenities'] 数组轻松找到复选框:

    1. 首先,为选中的便利设施创建一个空数组 ($amenities_checked)。
    2. 然后,使用isset($_POST["property_amenities"]) 检查是否有任何已检查的便利设施。如果是这样,请更新上面创建的数组的值。
    3. while 循环中,检查设施名称是否在该数组中。

    步骤 1 和 2 的代码:

    # Initialise an array to store the amenities checked.
    $amenities_checked = [];
    
    # Check whether the form has been submitted.
    if (isset($_POST["list_property"])) {
        # Initialise the amenities string.
        $property_amenities = "";
    
        # Check whether any checkbox has been checked.
        if (isset($_POST["property_amenities"])) {
            # Update the checked amenities array.
            $amenities_checked = $_POST["property_amenities"];
    
            # Implode the array into a comma-separated string.
            $property_amenities = implode(",", $amenities_checked);
        }
    }
    

    第 3 步的代码:

    # Iterate over every amenity.
    while ($row = $stm -> fetch()) {
      # Cache the id and name of the amenity.
      list($amenity_id, $amenity_name) = [$row["amenity_id"], $row["amenity_name"]];
    
      # Check whether the name of the amenity is in the array of the checked ones.
      $checked = in_array($amenity_name, $amenities_checked) ? "checked" : "";
    
      # Insert the HTML code in the list array.
      $List[] = "<label class = checkbox>
                    <input type = checkbox name = 'property_amenities[]'
                           value = '$amenity_name' $checked/>
                    $amenity_name
                 </label>";
    }
    

    完整代码:

    (sn-p用来折叠代码)

    <?php
      $db_host = "localhost";
      $db_name = "cl43-realv3";
      $db_user = "root";
      $db_pass = "";
    
      # Create a PDO database connection.
      try {
        $DB_con = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
        $DB_con -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      }
      catch (PDOException $e) {
        $e -> getMessage();
      }
    
      # Initialise an array to store the amenities checked.
      $amenities_checked = [];
    
      # Check whether the form has been submitted.
      if (isset($_POST["list_property"])) {
        # Initialise the amenities string.
        $property_amenities = "";
        
        # Check whether any checkbox has been checked.
        if (isset($_POST["property_amenities"])) {
          # Update the checked amenities array.
          $amenities_checked = $_POST["property_amenities"];
          
          # Implode the array into a comma-separated string.
          $property_amenities = implode(",", $amenities_checked);
        }
      }
    ?>
    <!DOCTYPE html>
    <html>
      <body>
        <form action = "<?= htmlspecialchars($_SERVER["PHP_SELF"]);?>" method = "post">
          <div class = "row clearfix">
            <div class="col-lg-12 col-md-6 col-sm-12">  
              <?php
                # Fetch the amenities.
                $stm = $DB_con->prepare("SELECT * FROM property_amenities");
                $stm -> execute([]);
    
                # Iterate over every amenity.
                while ($row = $stm -> fetch()) {
                  # Cache the id and name of the amenity.
                  list($amenity_id, $amenity_name) = [$row["amenity_id"], $row["amenity_name"]];
                  
                  # Check whether the name of the amenity is in the array of the checked ones.
                  $checked = in_array($amenity_name, $amenities_checked) ? "checked" : "";
                  
                  # Insert the HTML code in the list array.
                  $List[] = "<label class = checkbox>
                               <input type = checkbox name = 'property_amenities[]' value = '$amenity_name' $checked/>
                               $amenity_name
                             </label>";
                }
                
                # Save the number of amenities.
                $allamenities = $stm -> rowCount();
              
                # Determine the number of chunks.
                $how_many_chunks = $allamenities / 3;
                $roster_chunks = array_chunk($List, round($how_many_chunks), true);
              ?>
    
              <label>Property Amenities</label>
    
              <?php
                # Iterate over every chunk.
                foreach ($roster_chunks as $roster_chunk_key => $roster_chunk_value) {
                  echo "<div class='col-lg-3 col-md-6 col-sm-12'>" . join($roster_chunk_value) . "</div>";
                }
              ?>
            </div> 
          </div>
          <button type = "submit" class = "btn btn-primary" name = "list_property">SUBMIT PROPERTY</button>
        </form>
      </body>
    </html>

    【讨论】:

    • 这是在插入数据库之前。就在 $_POST 之后。假设在服务器端表单验证期间。
    • 还是不行。我什至复制粘贴了你的代码。仍然显示未选中。请在你的机器上试一试,然后告诉我。问候。
    • 我很高兴能帮助@BensonOThomas ?
    【解决方案2】:

    首先,您从 property_listings 表中获取数据并使用explode 函数将您的property_amenities 字符串转换为数组。然后你可以使用 in_array() 函数来检查你的字符串。如果 amenity_name 存在于您的数组中,那么您可以使用 checked 属性。

    例如。

    $stm = $DB_con->prepare("SELECT * FROM property_amenities");
    $stm->execute(array());
    
    // fetch data from property_amenities then use explode function
    $property_amenities = explode(",",$data);
    
          while ($row = $stm->fetch()){
            $amenity_id = $row['amenity_id'];
            $amenity_name = $row['amenity_name']; 
            $List[] ="<label class=checkbox> <input type=checkbox name='property_amenities[]' value='$amenity_name' <?php if(in_array($amenity_name,$property_amenities)){ echo "checked=true"; }?>> $amenity_name</label>";
          } 
    

    【讨论】:

      猜你喜欢
      • 2016-08-23
      • 2015-10-18
      • 2023-03-14
      • 2021-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-05
      相关资源
      最近更新 更多