开发者

How to use jquery to populate a second select list based on a first selected option

开发者 https://www.devze.com 2022-12-21 10:32 出处:网络
I am trying to dynamically change the options in a second select list using jquery depending on which item in the first select list is selected.

I am trying to dynamically change the options in a second select list using jquery depending on which item in the first select list is selected.

The second select list also needs to have optgroups in it.

How would I go about doing this?

Th开发者_高级运维anks


there are some plugins that do this. do a search for linked select lists.

one example can be found here http://manuel.radiohead.cl/proyectos/jquery/popdrodown/


Here's an example using JSON as the data exchange format. You could use XML, JSON, HTML or even pass javascript to be evaluated.

PHP:

$searchParam = $_GET['SEARCH_PARAM'];

//Get the matching results for the secondselect from your database
$results = $DB->query('Select ID, NAME, GROUP from mytable where parent = ?', $searchParam); 

//If you're using a PHP 5.2 or a newer version you have the json_encode function
print json_encode($results);

HTML:

<select id="firstselect" onchange="myfunc();">
  <option value="">Select one...</option>
  <option value="1">One option</option>
  <option value="2">Second choice</option>
</select>

<select id="secondselect"></select>

Javascript:

function myfunc() {
  var value = $("#firstselect").val();
  $.get("myjsonprovider.php", 
    {SEARCH_PARAM: value },
    dataType: "JSON",
    function(data) {
      var options = '<option value="">Select one...</option>';
      var optgroup = data[0].GROUP;
      options += '<optgroup label="' + data[i].GROUP + '">';
      for(var i = 0; i < data.length; i++) {
        if(optgroup != data[i].GROUP) {
          options += '</optgroup><optgroup label="'+data[i].GROUP+'">';
        }
        options += '<option value="' + records[i].ID +'">'+data[i].NAME+'</option>';
      }
      options += '</optgroup>';
      $("#secondselect").html(options);
    }
  );

}
0

精彩评论

暂无评论...
验证码 换一张
取 消