Reputation: 1339
I have a js function that shows different messages when an option from select is clicked.
I am using .onchange
to fire the messages.
What I am trying to achieve as well is to show the correct message if you load the HTML and an option is already selected. So somehow I guess to combine change and load.
Here is my HTML
<div class="row">
<div class="col-md-4">
<div class="form-group"><label for="cat">Category</label>
<select name="cat" id="cat" class="form-control" size="5">
<option value="General">General</option>
<option value="Rooms">Rooms</option>
<option value="Restaurant">Restaurant</option>
<option value="Spa">Spa</option>
<option value="Massages" selected>Massages</option>
</select>
</div>
</div>
<div class="col-md-8">
<div class="form-group"><label for="cat">Category explanation</label>
<div class="alert alert-secondary show_general" style="display:none;"><strong>General: </strong>The general category </div>
<div class="alert alert-secondary show_rooms" style="display:none;"><strong>Rooms: </strong>The rooms category </div>
<div class="alert alert-secondary show_restaurant" style="display:none;"><strong>Restaurant: </strong>The </div>
<div class="alert alert-secondary show_spa" style="display:none;"><strong>Spa: </strong>The Spa category </div>
<div class="alert alert-secondary show_massages" style="display:none;"><strong>Massages: </strong>The massages category carousel </div>
</div>
</div>
</div>
The JS
$('#cat').on('change load',function load_msg() {
if ($(this).val() == 'General') { $('.show_general').show(); } else { $('.show_general').hide(); }
if ($(this).val() == 'Rooms') { $('.show_rooms').show(); } else { $('.show_rooms').hide(); }
if ($(this).val() == 'Spa') { $('.show_spa').show(); } else { $('.show_spa').hide(); }
if ($(this).val() == 'Restaurant') { $('.show_restaurant').show(); } else { $('.show_restaurant').hide(); }
if ($(this).val() == 'Massages') { $('.show_massages').show(); } else { $('.show_massages').hide(); }
});
I have tried to use .onload
together with change
but can't figure out why it is not working
Upvotes: 0
Views: 462
Reputation: 4401
Instead of triggering onload, you need to trigger the .change() event of the dropdown. This triggers the same function as if someone selected/changed the dropdown. I have also optimized the code.
$('#cat').on('change',function load_msg() {
$('.alert-secondary').hide();
$('.show_'+ $(this).val().toLowerCase()).show();
});
$('#cat').change();
Upvotes: 1