Camillia
asked on
How can I hide some options in a dropdown?
If I have a dropdown that renders like this:
I have another one, State, that renders like this
1. User selects Canada from dropdown and the ID is 25.
2. I want to hide all the options that have "-126" in them. Is this possible?
I think I need to have
1. .change event for countryId dropdown
2. Get $('#CountryId).val()
3. Now, do I need to loop thru the States select/dropdown?
<select data-val="true" data-val-number="The field CountryId must be a number." data-val-required="Country Required" id="CountryId" name="CountryId"><option value="Selects items">Country*</option>
<option value="25">Canada</option>
<option value="126">United States</option>
</select>
I have another one, State, that renders like this
<select data-val="true" data-val-number="The field StateId must be a number." data-val-required="State Required" id="StateId" name="StateId"><option value="Selects items">State*</option>
<option value="115-126">Armed Forces - Americas</option>
<option value="116-126">Armed Forces - Europe</option>
<option value="169-25">Alberta</option>
<option value="170-25">British Columbia</option>
</select>
1. User selects Canada from dropdown and the ID is 25.
2. I want to hide all the options that have "-126" in them. Is this possible?
I think I need to have
1. .change event for countryId dropdown
2. Get $('#CountryId).val()
3. Now, do I need to loop thru the States select/dropdown?
ASKER
Let me try. You're a life saver if this works :) I've been at this almost all day and now working off hours to get this working. I'll post back.
Here's an optimized version:
Demo: http://jsfiddle.net/AlexCode/cLsm12kd/
$('#CountryId').on('change', function(){
var value = this.value,
$options = $('#StateId option');
$options.hide();
$options.filter('[value$="-' + value + '"]').show();
});
Demo: http://jsfiddle.net/AlexCode/cLsm12kd/
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
be sure to test @Alexandre Simões solution on non-recent browsers
ASKER
Let me try both. Thank you both for helping me out on this.
True @leakim971, it doesn't even work on latest IE.
Here's the modified version that works everywhere :)
Here's the modified version that works everywhere :)
var $options = $('#StateId option');
$('#CountryId').on('change', function(){
var value = this.value,
$target = $('#StateId');
$target.empty();
$target.html($options.filter('[value$="-' + value + '"]'));
});
ASKER
Will try soon and post back.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I can't believe that this works! I can't thank you both enough.
I have another question along the same line. I'll open a new question now.
I have another question along the same line. I'll open a new question now.
Open in new window