Domanda

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;}
È stato utile?

Soluzione

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:

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top