Nightwolf
Nightwolf

Reputation: 951

Why doesn't my Jquery code work more than once on my dropdown?

I have created a dropdown in html id tagged as "area" with values. Another dropdown tagged as car with optgroups of the areas and a full list of cars.

What I am trying to accomplish is to filter the too long dropdown of cars into a smaller manageable list, and thus my reason for the first dropdown of area.

The Jquery code below hides the full list of cars and creates a temporary dropdown with just the selected optgroup data:

$('select#car').after('<select id="parkingLot"><option value="0">ALL</option></select>');
$('select#car').hide();
$('select#area').change(function() {
  var area = $(this).val();
  $("#parkingLot").html($('select#car optgroup[label="' + area  + '"]'));
});

This code works, but only once per optgroup. Example: if you select area 1 and check the second dropdown it displays correctly, then check area 2 and it display correctly, however area 1 does not work after checking it again.

Any help will be appreciated.

Upvotes: 1

Views: 74

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388326

I think it is because you are moving the optgroup from the original select

$('#car').after('<select id="parkingLot"><option value="0">ALL</option></select>');
$('#car').hide();
$('#area').change(function() {
  var area = $(this).val();
  $("#parkingLot").html($('#car optgroup[label="' + area + '"]').clone());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="car">
  <optgroup label="a1">
    <option>a1.1</option>
    <option>a1.2</option>
  </optgroup>
  <optgroup label="a2">
    <option>a2.1</option>
    <option>a2.2</option>
  </optgroup>
  <optgroup label="a3">
    <option>a3.1</option>
    <option>a3.2</option>
  </optgroup>
  <optgroup label="a4">
    <option>a4.1</option>
    <option>a4.2</option>
  </optgroup>
</select>
<select id="area">
  <option></option>
  <option>a1</option>
  <option>a2</option>
  <option>a3</option>
  <option>a4</option>
</select>

Upvotes: 3

Related Questions