Reputation: 984
I have this code below here, to control which color block to show on hide on toggling on a dropdown list.
However it only works when I make a change on the dropdown list (ie, select a color). But I need it to display the right color block on load too.
Right now its displaying #red_ok on default regardless of the "value" onload.
How do I edit this code to achieve this?
$(function () {
$("#product-select-option-1").change(function() {
var val = $(this).val();
if(val === "Red") {
$("#red_ok").css({"display":"block"});
$("#yellow_ok").css({"display":"none"});
}
else if(val === "Yellow") {
$("#yellow_ok").css({"display":"block"});
$("#red_ok").css({"display":"none"});
} }); });
.
#red_ok {width:25px; height:25px; background:#c40314;}
#yellow_ok {display:none; width:25px; height:25px; background:#f5d116;}
Upvotes: 1
Views: 140
Reputation: 253348
Simply trigger the change
event manually:
$(function () {
// binds the change event-handler:
$("#product-select-option-1").change(function () {
var val = $(this).val();
if (val === "Red") {
$("#red_ok").css({
"display": "block"
});
$("#yellow_ok").css({
"display": "none"
});
} else if (val === "Yellow") {
$("#yellow_ok").css({
"display": "block"
});
$("#red_ok").css({
"display": "none"
});
}
// triggers the change event:
}).change();
});
The above can, however, be reduced, and simplified, to:
$(function () {
$("#product-select-option-1").change(function () {
$('div[id$="ok"]').hide();
$('#' + this.value.toLowerCase() + '_ok').show();
}).change();
});
References:
Upvotes: 4