js根据所选的其他选项显示选项

时间:2015-08-24 06:22:48

标签: javascript php mysql

我有一个包含运输行的选择字段,如下所示

<select>
    <option >cma</option>
   <option>uafl</option>
</select>

和另一个包含船只的选择字段如下

<select>
    <option >apulia</option>
    <option>costa</option>
    <option >beinjin</option>
    <option>union</option>
</select>

当用户选择一条航线时说CMA我想要包含船只的选择选项,显示与CMA关联的船只只说COSTA和BEINJIN

这些数据将从mysql数据库中提取。

请帮助,我将非常感激。感谢。

1 个答案:

答案 0 :(得分:0)

注意:

  • 您需要使用Ajax来实现目标
  • 我将使用jQuery,一个javascript库,你可以下载here然后将它存储在你的项目文件夹中

代码(select.php):

<html>
<head>
  <script src="jquery-1.9.1.min.js"></script> <!-- REPLACE NECESSARY JS FILE DEPENDING ON THE VERSION YOU HAVE DOWNLOADED -->
  <script type="text/javascript">

    $(document).ready(function(){ /* START JQUERY */
      $("#base-select").change(function(e){ /* EVERYTIME A SHIP IS SELECTED */
        e.preventDefault(); /* PREVENT FROM REFRESHING THE PAGE */
        var base = $("#base-select").val(); /* STORE THE SELECTED SHIP TO THIS VARIABLE */
        var dataString = "base="+base; /* STORE THE DATA IN A DATA STRING */

        $.ajax({ /* START THE AJAX */
          type: "POST", /* METHOD YOU WILL BE USING TO SUBMIT VALUE OF THE SELECTED SHIP */
          url: "get-options.php", /* THE TARGET FILE ON WHERE YOU WILL PASS THE VALUE OF THE SELECTED SHIP */
          data: dataString, /* THE DATA YOU WILL BE PASSING */
          success: function(result){
            $("#select").empty().append(result); /* CLEAR THE CURRENT OPTIONS OF THE SECOND SELECT FIELD AND UPDATE DEPENDING ON THE SELECTED SHIPS */
          } /* END OF SUCCESS */
        }); /* END OF AJAX */

      }); /* END OF CHANGE FUNCTION */
    });

  </script>
</head>

<body>

  <select id="base-select">
    <option disabled selected>Select Shipping Line</option>
    <option value="1">CMA</option>
    <option value="2">UAFL</option>
  </select>

  <select id="select">
    <option disable>Select first a Shipping Line</option>
  </select>

</body>
</html>

GET-options.php:

<?php

  if(!empty($_POST["base"])){
    if($_POST["base"] == 1){
      ?>
        <option>COSTA</option>
        <option>BEIJIN</option>
      <?php
    }
    else if($_POST["base"] == 2){
      ?>
        <option>APULIA</option>
        <option>UNION</option>
      <?php
    }
  }    

?>