Jquery Add Values to Select Options

后端 未结 3 960
梦如初夏
梦如初夏 2021-01-16 18:36

I have googled this option for many days but I couldn\'t find a solution.

What I want is:

  1. I have two Select Box
  2. First Select Box have Country
相关标签:
3条回答
  • 2021-01-16 18:55

    The "cascading dropdown" is such a common interface - I find it hard to believe that you couldn't find any examples. Here's a PHP example that will point you in the right direction.

    0 讨论(0)
  • 2021-01-16 18:56

    Assumption

    • You have a script ("/getCities.php") that takes a parameter ("country") that is the ID of the country you want the cities of and outputs JSON that looks like this:

      {"Cities":
      [
          {
              "ID": 1,
              "Name": "New York"
          },
          {
              "ID": 2,
              "Name": "Los Angeles"
          }
      ]}
      

      (You can use JSONLint to validate your JSON.)

    Then maybe something along these lines:

    <select id="Countries">
        <!-- omitted -->
    </select>
    <select id="Cities"></select>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        // when a new country is selected...
        $("#Countries").change(function() {
          // ...clear existing cities...
          $("#Cities").empty();
          // ...and repopulate cities based on JSON data.
          $.getJSON( "/getCities.php",
          // pass the selected country ID
            {
              country: $("#Countries").val()
            },
            function(data) {
              $.each(data.Cities, function(n, city) {
                  // add a new option with the JSON-specified value and text
                  $("<option />").attr("value", city.ID).text(city.Name).appendTo("#Cities");
              });
            }
          );
        }); // $("#Countries").change(function() { ... });
      }); // $(document).ready(function() { ... });
    </script>
    
    0 讨论(0)
  • 2021-01-16 19:00

    try this.

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    
    <script type="text/javascript">
        function moveItem() {
            $("#target").append($("#source").find(':selected'));
        }
    </script>
    
    <select id="source" size="3">
        <option>option1</option>
        <option>option2</option>
        <option>option3</option>    
    </select>
    
    <button onclick="moveItem()">Move Item</button>
    
    <select id="target" size="3"></select>
    
    0 讨论(0)
提交回复
热议问题