Geril
Geril

Reputation: 159

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:

<dl>
    <dt><label for="typ">Typ</label></dt>
    <dd>
    <select id="typ" size="1">
        <option value="1">Normálna</option>
        <option value="0">Presmerovanie</option>
    </select>
    </dd>
</dl>
<!-- Len ak je presmerovatelna -->
<div id="pres" style="display: none;">
    <dl>
        <dt><label for="presmerovat">Presmerovat na</label></dt>
        <dd>
        <select id="presmerovat" size="1">
            <option>Category 1</option>
            <option>Category 2</option>
        </select>
        </dd>
    </dl>
</div>
<!-- Koniec ak je presmerovatelna -->

is it possible?

Upvotes: 1

Views: 670

Answers (2)

Shadow Wizard
Shadow Wizard

Reputation: 66399

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

<select id="typ" size="1">
    <option value="1" data-rel="norm">Normálna</option>
    <option value="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.

Upvotes: 0

Zoltan Toth
Zoltan Toth

Reputation: 47657

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

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

demo

Upvotes: 5

Related Questions