kurama-rho kurama-rho - 6 months ago 58
Javascript Question

How to Hide select option list dependent from select option using jQuery

Hallo guys i ve some problem in ajax to hide option from select option list, it work in but not work in option. Like this :

<label>Province</label>
<select class="form-control" name="province" id="province">
<option value="prov001"> Prov 001</option>
<option value="prov002"> Prov 002</option>
<option value="prov003"> Prov 003</option>
</select>

<label>City</label>
<select class="form-control" name="city" id="city">
<option class="cty" id="prov001" value="city001"> City 001</option>
<option class="cty" id="prov002" value="city002"> City 002</option>
<option class="cty" id="prov003" value="city003"> City 003</option>
<option class="cty" id="prov001" value="city004"> City 004</option>
<option class="cty" id="prov002" value="city005"> City 005</option>
<option class="cty" id="prov003" value="city006"> City 001</option>
</select>


and this the ajax :

$(function() {
$('#province').change(function(){
$('.cty').hide();
$('#' + $(this).val()).show();
});
});


before this i use in div works but in option not, thanks

Answer

In the select list options, you have multiple id's that are the same - you need to change these to be classes and modify the js:

//js
$(function() {
    $('#province').change(function(){
        $('.cty').hide();
        $('.' + $(this).val()).show();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Province</label>
<select class="form-control" name="province" id="province">
        <option value="prov001"> Prov 001</option>
        <option value="prov002"> Prov 002</option>
        <option value="prov003"> Prov 003</option>              
</select>

<select class="form-control" name="city" id="city">
        <option class="cty prov001" value="city001"> City 001</option>
        <option class="cty prov002" value="city002"> City 002</option>
        <option class="cty prov003" value="city003"> City 003</option>
        <option class="cty prov001" value="city004"> City 004</option>
        <option class="cty prov002" value="city005"> City 005</option>
        <option class="cty prov003" value="city006"> City 001</option> 
</select>