Skip to content Skip to sidebar Skip to footer

Jquery On Select Show Div

i have one question about jQuery. If user select 'Presmerovanie' with value '0' in html select with id 'typ' i want to show div with id 'pres' . Here is the code:
&

Solution 1:

$("#typ").on("change", function() {
    $("#pres").hide();

    if ( $(this).val() == '0' ) {
        $("#pres").show();
    } 
});​

demo

Solution 2:

To make it flexible you can add data attributes to the drop down items:

<selectid="typ"size="1"><optionvalue="1"data-rel="norm">Normálna</option><optionvalue="0"data-rel="pres">Presmerovanie</option></select>

Then bind the change event and handle the selection:

$(document).ready(function() {
    $("#typ").on("change", function() {
        $(this).find("option").each(function() {
            var rel = $(this).data("rel"); 
            if (rel && rel.length > 0) {
                var obj = $("#" + rel);
                if ($(this).is(":selected"))
                    obj.show();
                else
                    obj.hide();
            }
        });
    });

    //show initial item:
    $("#typ").change();
});​

This will show only the related element of the selected item and hide all others.

Live test case.

Post a Comment for "Jquery On Select Show Div"