user1322720
user1322720

Reputation:

JS function to listen to select element and change CSS style depending on the selected option?

I have a select element and a div:

<select>
    <option value="v_1"></option>
    <option value="v_2"></option>
    <option value="v_3"></option>
</select>
<div id="div_id"></div>

If the user selects option 3, I want the div to get display:block. If option 1 or 2 are selected, the div should get display:none. So if you change the selection, the div appears and disappears.

I can do this with:

<option onClick="document.getElementById('div_id').style.display = 'block'">

but I find this creates confusing and redundant code, if I have many options.

How can I define a function that "listens" to what happens at the select element and displays or hides the div according to the selected option?

Upvotes: 0

Views: 5103

Answers (1)

dcodesmith
dcodesmith

Reputation: 9614

Use the onchange event on a select element/tag and not an onclick event.

HTML

<select onchange="toggle(this)">
    <option value="">-- please choose --</option>
    <option value="v_1">1</option>
    <option value="v_2">2</option>
    <option value="v_3">3</option>
</select>
<div id="div_id">Some Data</div>

JS (by value) JSFiddle

function toggle(el){
    var value = el.options[el.selectedIndex].value,
        div = document.getElementById('div_id');

    if (value === 'v_1' || value === 'v_2') {
        div.style.display = 'none';
    } else if (value === 'v_3') {
        div.style.display = 'block';
    }
}

JS (by index)

function toggle(el){
    var idx = el.selectedIndex,
        div = document.getElementById('div_id');

    if (idx <= 1) {
        div.style.display = 'none';
    } else if (idx >= 2) {
        div.style.display = 'block';
    }
}

Upvotes: 3

Related Questions