tags:

views:

125

answers:

2

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

Thanks

A: 

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/

Josh
A: 

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);
    }
  );

}
RenderIn
Thank you for your response, I've one question though, how would I format my PHP file?
Probocop
I updated the example with some sample PHP code. I also slightly modified the $.get call in the Javascript part by adding a dataType: parameter and removing the JSON.parse(data) manipulation as it's unnecessary.
RenderIn