0
votes

How to make a select list with dynamic options?

I have two select list; I have two options on my first select list, each one have a different list of options in another select list.

If I choose the first select option, the second list should have a different values.

First Select                           Second Select
-----------------                      -----------------                         
Option selected: [0] StackOverflow         Options Available:
Another option: [1] GitHub                   Ask a Question
                                             Answer a Question
-----------------     ---->            -----------------

or if the second value is selected

First Select                           Second Select
-----------------                      -----------------                         
Option selected: [1] GitHub                Options Available:
Another option: [0] StackOverflow            Post a New Repository
                                             Fork a Repository
-----------------     ---->            -----------------

I also use PHP with MySQL to display values (options) in the select. In first select, I use to display all the possible options with MySQL, then echo it out.

The second select list need the ID from the previously selected so it can select it. Example SQL code: "SELECT * FROM sections WHERE id = ?". I'm new to PHP and to AJAX, I also see this question but it just doesn't work for me. Sorry for re-asking this dumb question again.

1

1 Answers

0
votes

Initially, Hide the second selectbox. Add an onchange function to first selectbox in jquery. Like below.

If the second select box has static.

$('.firstselect').onchange(function() {
  var first_val = $(this).val();

  if ( first_val === 0 ) {
    $('stack_select').show();
    $('github_select').hide();

  } else if( first_val === 1 ) {
    $('stack_select').hide();
    $('github_select').show();
  }

});

If the second select box has dynamic. Make an ajax request and load the content dynamically using jquery append method.