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>
Here's little improvement to Milind Anantwar's answer, considering urbz's comment:
$('#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>
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With