Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery dependent select options

Tags:

jquery

I have a large database and i want display options in second select depending on the value of the first select using jQuery.

I want when I select for example option with value 1 for first select, display in 2nd selet options with value 1.

Can you help me with an example?

First select

<select id="city" name="city">
<option value="0">Select City</option>
<option value="1">Manchester</option>
<option value="2">Leicester</option>
<option value="3">Londra</option>
</select>

Second select

<select id="street" name="street">
<option value="0">Select Street</option>
<option value="1">Street 1</option>
<option value="1">Street 2</option>
<option value="1">Street 3</option>
<option value="2">Street 4</option>
<option value="2">Street 5</option>
<option value="2">Street 6</option>
.....
<option value="1200">Street 7</option>
<option value="1200">Street 8</option>
<option value="1200">Street 9</option>
</select>
like image 416
mIH1 Avatar asked Dec 19 '22 15:12

mIH1


2 Answers

Here's little improvement to Milind Anantwar's answer, considering urbz's comment:

  • now code selects first of streets of selected city
  • if there's no street for city select element resets

$('#city').change(function() {
  $('#street option').hide();
  $('#street option[value="' + $(this).val() + '"]').show();
  // add this code to select 1'st of streets automaticaly 
  // when city changed
  if ($('#street option[value="' + $(this).val() + '"]').length) {
    $('#street option[value="' + $(this).val() + '"]').first().prop('selected', true);
  }
  // in case if there's no corresponding street: 
  // reset select element
  else {
    $('#street').val('');
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="city" name="city">
  <option value="0">Select City</option>
  <option value="1">Manchester</option>
  <option value="2">Leicester</option>
  <option value="3">Londra</option>
</select>

<select id="street" name="street">
  <option value="0">Select Street</option>
  <option value="1">Street 1</option>
  <option value="1">Street 2</option>
  <option value="1">Street 3</option>
  <option value="2">Street 4</option>
  <option value="2">Street 5</option>
  <option value="2">Street 6</option>
  <option value="1200">Street 7</option>
  <option value="1200">Street 8</option>
  <option value="1200">Street 9</option>
</select>
like image 198
Artem S. Avatar answered Jan 11 '23 22:01

Artem S.


This should be rather straight forward:

$('#city').change(function(){
    $('#street option')
        .hide() // hide all
        .filter('[value="'+$(this).val()+'"]') // filter options with required value
            .show(); // and show them
});
like image 36
techfoobar Avatar answered Jan 11 '23 22:01

techfoobar