user1395909
user1395909

Reputation: 167

JavaScript: How do I make a div's style dependent on option chosen in select box?

JavaScript

function displayContent()
    {
        var 1 = getElementById(1);
        var 2 = getElementById(2);
        var 3 = getElementById(3);
        var 4 = getElementById(4);

        if(document.form.list.selectedIndex==0) {
        1.style.display = "block";
        }
        if(document.form.list.selectedIndex==1) {
        2.style.display = "block";
        }
        if(document.form.list.selectedIndex==2) {
        3.style.display = "block";
        }
        if(document.form.list.selectedIndex==3) {
        4.style.display = "block";
        }
    }

HTML

   <form id="form">
    <select onchange="displayContent();" id="list">
                        <option>1</option>
                        <option>2</option>
                        <option>3</option>
                        <option>4</option>
                    </select>
    </form>
    <div id="1">Content1</div>
    <div id="2">Content2</div>
    <div id="3">Content3</div>
    <div id="4">Content4</div>

This is the script and markup that I have put together. I've tried a few different ways before this but all of them result in the same non-solution, just like this one. Nothing happens when I change the option in the select box. Have I missed something?

By default, all the divs are set to display:none;.

Thanks, Jo

Upvotes: 1

Views: 273

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337610

There are several issues with your code, including missing document. from getElementById, not giving your form or select elements a name attribute so you can reference them in js, attempting to create a variable which begins with an integer and having id attributes which begin with integers.

With all that in mind, try this:

function displayContent() {
    var div1 = document.getElementById("div1");
    var div2 = document.getElementById("div2");
    var div3 = document.getElementById("div3");
    var div4 = document.getElementById("div4");

    if(document.form.list.selectedIndex==0) {
        div1.style.display = "block";
    }
    if(document.form.list.selectedIndex==1) {
        div2.style.display = "block";
    }
    if(document.form.list.selectedIndex==2) {
        div3.style.display = "block";
    }
    if(document.form.list.selectedIndex==3) {
        div4.style.display = "block";
    }
}

Example fiddle


Also note that this can be massively simplified:

function displayContent() {
    document.getElementById("div" + (document.form.list.selectedIndex + 1)).style.display = "block";
} 

Example fiddle

Upvotes: 2

mohana rao
mohana rao

Reputation: 429

instead of

getElementById

use

document.getElementById('1');
document.getElementById('2');
document.getElementById('3');
document.getElementById('4');

Upvotes: 0

Related Questions