Jhilke Dai Jhilke Dai - 3 months ago 42x
jQuery Question

Hierarchical Select List using jQuery

I have two select list,

Select list 1 contains the Mobile phone brands names

<select name="mobile-phone" class="mobile-phone">
<option value="Select">Select</option>
<option value="Nokia">Nokia</option>
<option value="Samsung">Samsung</option>
<option value="HTC">HTC</option>
<option value="Apple">Apple</option>

Select list 2 contains the phone type like

<select name="mobile-model" class="mobile-model">
<option value="Select">Select</option>
<option value="Nokia--Lumia-520">Lumia 520</option>
<option value="Nokia--Lumia-620">Lumia 620</option>
<option value="Samsung--Galaxy-s3">Galaxy S3</option>
<option value="Samsung--Galaxy-s4">Galaxy S4</option>
<option value="HTC--hero">Hero</option>
<option value="HTC--one">One</option>
<option value="Apple--iphone4">iPhone 4</option>
<option value="Apple--iphone5">iPhone 5</option>

My quest is I want to display Select list 2 according to the value users select in Select List 1.

If a user selects Nokia in first selection, then only Lumia phones should be shown in second select list. Like so, for other phones.

When None is selected in First select list, then second select list should not show anything, but still visible without any option (like disabled button).

How can I accomplish this using jQuery?

The JSFiddle I have made from above select list.


I think you are looking for:

$("#sel2").prop("disabled", true);

$( "#sel1" ).change(function() {
  var value = $(this).val();
    $("#sel2").prop("disabled", false);
    $("#sel2 > option").hide();
    $("#sel2 > option[value*='" + value +"']").show();

Only I put to selects Id for do the selection by Jquery more easy. Before I disabled the control wating for any selection, and when the first select change only I keep the option that macth with option[value*='" + value +"']".

Live demo here