wsgg
wsgg

Reputation: 984

option value controlling css

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

Answers (1)

David Thomas
David Thomas

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();
});

JS Fiddle demo.

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();
});

JS Fiddle demo.

References:

Upvotes: 4

Related Questions