簡體   English   中英

頁面提交並重新加載后,如何保持復選框處於選中狀態?

[英]How can I retain checkboxes checked state after page submit and reload?

我有一個名為property_amenities的表,該表具有列; amenity_idamenity_name其值作為復選框填充在表單上。 提交表單后,將檢查后的值作為數組插入到property_listings列的property_amenities表中。

    <?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');

只需在數據庫中檢入選中了哪些復選框,並在您回顯復選框時將那些checked屬性包括在內:

$checked = (condition) ? "checked" : "";

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

編輯:

(回應評論

由於每個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>";
}

完整的代碼:

(該代碼段用於折疊代碼)

 <?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> 

首先,您從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>";
      } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM