Hide select option value so user can't view it
So I am creating a list of drop downs. I retrieve data from my database of
3 general locations. Countries, Regions/States/Providences and Cities. So
I have 3 drop downs (one for each of these general locations). And when a
Country is selected I want only the regions within that Country to be an
option. I put all regions in the select tag because I do not know what
country the user is going to select and I am trying to avoid an AJAX call
to use PHP.
My Current HTML:
<select id='countrySelect'>
<option value='0'>Select Country</option>
<option value='1'>United States</option>
<option value='2'>Canada</option>
</select>
<select id='regionSelect' disabled>
<option value='0'>Select Region/State</option>
<option value='1' data-id='1'>California</option>
<option value='2' data-id='2'>British Columbia</option>
</select>
<select id='citySelect' disabled>
<option value='0'>Select City/Area</option>
<option value='1' data-id='1'>San Fransisco</option>
<option value='2' data-id='1'>Los Angeles</option>
<option value='3' data-id='2'>Victoria</option>
<option value='4' data-id='2'>Vancouver</option>
</select>
The value corresponds to the idea of that location in the database
(Countries, Regions, and Cities are each their own database). Data-id
refers to the id of where that option is located. For example:
California's data-id is 1 meaning it is in country 1. And the United
States has a value of 1 so therefore California is in the United States.
It works the same for cities in regions. But when a user clicks Unites
States. I want British Columbia to not BE SEEN (not disabled, they are
still visible and not removed because they are gone forever). I want a
cross browser way to hide them and if they choose Canada then everything
else will be 'hidden' from the user. I only made it for the Country and
Region so far. The city doesn't work yet because I wanted to figure this
out first.
My current jQuery:
$('#countrySelect').on('change', function() {
// set the country ID equal to the selected value
var countryId = this.value;
// enable all regions to be selected
$("#regionSelect > option").prop('disabled', false);
// loop through to disable regions that cannot be selected
$("#regionSelect > option").each(function() {
if($(this).data('id')!= countryId && $(this).val() != 0) {
$(this).hide():
}
});
// if a country was selected allow the user to select a region
if(countryId > 0){
$('#regionSelect').prop('disabled',false);
}
else {
$('#regionSelect').prop('disabled',true);
$("#regionSelect").val('0');
}
});
No comments:
Post a Comment