如何在提交表单后保留下拉选项的值

时间:2017-02-04 21:21:13

标签: php jquery ajax html-select

我有三个下拉选项从数据库,状态和城市选择中提取数据。city select option使用ajax根据select in state值从数据库中获取值,一切正常,获取值。state value正在使用php function to populate

问题是第二个选择选项,city option在提交表单后没有保留选择选项栏中的值。 (基本上它重置)提交表单后的第二个问题是选择options of city没有填充,您需要更改另一个option of state,然后才能在城市列表中进行更改。

经历了许多主题和搜索,但无法找到解决方案。我认为在重新加载页面后值仍应保留,因为我使用localstorage进行类别和状态并且没有问题,即使city option的值在localstorage中只是在重新加载页面后它没有显示在select选项中

function get_state(){
  global $db;
  $output = '';
  $results = $db->query("SELECT * FROM region");
  foreach($results as $state) {
    $output .='<option value="'.$state["pk_i_id"].'">'.$state["s_name"].'</option>';
  }
  return $output;
}

 <form method="GET">
 <div class="container">
   <div class="form-group">

      <select name="categories" id="categories" class="btn-sm saveIt">
        <option value=""></option>
        <?=get_categories();?>
      </select>

      <select name="state" id="state" class="btn-sm saveIt">
        <option value=""></option>

        <?=get_state();?>
      </select>

      <select name="city" id="city" class="btn-sm saveIt">
        <option value=""></option>
      </select>


      <button type="submit" id="go">Go</button>


   </div>
 </div>
</form>

ajax脚本

$(document).ready(function() {
      function get_city(){
        var stateID = $('#state').val();
        $.ajax({
          url: '/parsers/city_list.php',
          type: 'POST',
          data: {stateID : stateID},
          success: function(data){
            $('#city').html(data);
          },
          error: function() {
            alert("Something went wrong with the city list.")
          },
        });
      }
      $('select[name="state"]').change(get_city);
    });

ajax调用的city_list.php

<?php
  require_once $_SERVER['DOCUMENT_ROOT'].'/core/init.php';
  $stateID = (int)$_POST['stateID'];

  $cityQuery = $db->query("SELECT * FROM city WHERE fk_i_region_id = '$stateID' ");
  ob_start();
  ?>
  <option value="">Select City</option>
  <?php while($city = mysqli_fetch_assoc($cityQuery)): ?>
    <option value="<?=$city['pk_i_id'];?>"><?=$city['s_name'];?></option>
  <?php endwhile; ?>

<?php echo ob_get_clean(); ?>

如果您需要我能提供的一些细节,请提前感谢。谢谢。

A link to sample code

此链接指向带有localstorage的jQuery插件。 [jquery插件] [1]。

提交表单前的显示只有在提交表单city option显示值而不是name of value后才能正常显示。

提交表单后的第二个问题只显示一个选项,它应显示所有选项,您需要先更改city options,然后显示所有city list

Problem two image link

1 个答案:

答案 0 :(得分:0)

另一个新版本

好的,我只是继续进行了一个没有数据库的工作演示,所以我可以尝试更好地理解你的问题。将其复制到您的本地计算机并检查它,看看它是否是您正在寻找的东西。如果按照您想要的方式运行,请查看我们是否可以通过数据库调用进行调整以满足您的需求。

首先,index.php文件:

<?php

$states = [
  0 => [
    'pk_i_id' => 0,
    's_name' => 'Montana'
  ],
  1 => [
    'pk_i_id' => 1,
    's_name' => 'Nebraska'
  ],
  2 => [
    'pk_i_id' => 2,
    's_name' => 'Idaho'
  ],
];

function get_state($states, $selectedID){

  $output = '';

  foreach($states as $state) {
    if ($state['pk_i_id'] == $selectedID) {
      $output .='<option selected value="'.$state["pk_i_id"].'">'.$state["s_name"].'</option>';
    } else {
      $output .='<option value="'.$state["pk_i_id"].'">'.$state["s_name"].'</option>';
    }
  }
  return $output;
}

?>

<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
  </head>
  <body>

    <form method="GET">
     <div class="container">
       <div class="form-group">

          <select name="categories" id="categories" class="btn-sm saveIt">
            <option value="">Categories</option>
          </select>

          <select name="state" id="state" class="btn-sm saveIt">
            <option value="">State</option>
            <?php 

              if (isset($_GET['state'])) {
                $stateID = $_GET['state'];
              } else {
                $stateID = -1;
              }

            ?>
            <?php echo get_state($states, $stateID); ?>
          </select>

          <select name="city" id="city" class="btn-sm saveIt">
            <option value="">City</option>
            <?php 

              if (isset($_GET['city'])) {
                echo "<input id=\"hiddenInput\" type=\"hidden\" value=\"{$_GET['city']}\">";
              }

            ?>
          </select>

          <button type="submit" id="go">Go</button>

       </div>
     </div>
    </form>

    <!-- jQuery first, then Tether, then Bootstrap JS. -->
   <script
  src="https://code.jquery.com/jquery-3.1.1.js"
  integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA="
  crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
    <script src="script.js" type="text/javascript" charset="utf-8" async defer></script>
  </body>
</html>

接下来是city_list.php文件:

<?php

  // Montana
  $cityList[0] = [
    0 => [
      'pk_i_id' => 0,
      'city_name' => 'Bozeman'
    ],
    1 => [
      'pk_i_id' => 1,
      'city_name' => 'Helena',

    ],
    2 => [
      'pk_i_id' => 2,
      'city_name' => 'Butte'
    ],
  ];

  // Nebraska
  $cityList[1] = [
    0 => [
      'pk_i_id' => 0,
      'city_name' => 'Omaha'
    ],
    1 => [
      'pk_i_id' => 1,
      'city_name' => 'Hastings',

    ],
    2 => [
      'pk_i_id' => 2,
      'city_name' => 'Lincoln'
    ],
  ];

  // Idaho
  $cityList[2] = [
    0 => [
      'pk_i_id' => 0,
      'city_name' => 'Boise'
    ],
    1 => [
      'pk_i_id' => 1,
      'city_name' => 'Twin Falls',

    ],
    2 => [
      'pk_i_id' => 2,
      'city_name' => 'Caldwell'
    ],
  ];

  ob_start();
  ?>
  <option value="">Select City</option>
  <?php foreach ($cityList[$_REQUEST['stateID']] as $city) {?>
    <?php if ($_REQUEST['selected'] == $city['pk_i_id']) : ?>
      <option selected value="<?=$city['pk_i_id'];?>"><?=$city['city_name'];?></option>
    <?php else: ?>  
      <option value="<?=$city['pk_i_id'];?>"><?=$city['city_name'];?></option>
    <?php endif; ?>
  <?php } ?>

<?php echo ob_get_clean(); ?>

最后,script.js:

$(document).ready(function() {

  function get_city(selected) {
    var stateID = $('#state').val();
    $.ajax({
      url: 'city_list.php',
      type: 'POST',
      data: {stateID : stateID, selected : selected},
      success: function(data){
        $('#city').html(data);
      },
      error: function() {
        alert("Something went wrong with the city list.")
      },
    });
  }

  $('select[name="state"]').change(function () {
    get_city(-1);
  });

  if ( $('select[name="state"]').val() != '') {
    var hiddenInput = document.getElementById('hiddenInput');
    if (!!hiddenInput) {
      get_city(hiddenInput.value);
    } else {
      get_city(-1);
    }
  }

});

将所有这些放在同一目录中,然后查看功能。如果这符合您的需求,请为您的项目进行调整!