简体   繁体   中英

Javascript switch statements display data from 2 drop down menus

Hi is there any possible way so I can display data between two options that I select from two dropdown menu options ?

<select id="mark">
<option value="blue">blue</option>
<option value="red">red</option>
 <option value="green">green</option>
 </select>

<select id="style">
 <option value="circle">circle</option>
 <option value="triangle">triangle</option>
 <option value="square">square</option>
 </select>

for instance if chose blue from the one box and triangle from the other box is there any possible way to get this ? here is my try. but it seems that this is not working. Any advice ? Thanks

    switch(document.getElementById('mark').value,('style').value)
   {
    case 'blue':case'circle':
        {
             do something here
        }
        break;
    case 'red':case'triangle':
                   {
                    do something here
                   }

        break;

 }

You need nested switch-cases like this:

var mark = document.getElementById('mark').value;
var style = document.getElementById('style').value;
switch(mark)
{
    case 'blue':
        switch (style) {
            case 'circle':
                functionOne();
                break;
            case 'triangle':
                functionTwo();
                break;
        }
        break;

    case 'red':
        switch (style) {
            case 'circle':
                functionThree();
                break;
            case 'triangle':
                functionFour();
                break;
        }
        break;
}

But I'd prefer something else. I can't say what exactly because I don't know what you wanna do. Anyway. I hope this helps.

Going off of Werner's answer, you could use string concatenation to achieve it with one switch if desired.

var mark = document.getElementById('mark').value;
var style = document.getElementById('style').value;
switch(mark + ' ' + style)
{
    case 'blue circle':
        functionOne();
        break;
    case 'blue triangle':
        functionTwo();
        break;
    case 'red circle':
        functionThree();
        break;
    case 'red triangle':
        functionFour();
        break;
}

不,不幸的是,您将始终必须使用嵌套开关。

You can try this:

document.getElementById("clickMe").onclick = function(){
    switch(document.getElementById('mark').value + '-' + document.getElementById('style').value) {
        case 'blue-circle':
                console.log('blue circle');
        break;
    }

}

http://jsfiddle.net/J3BK3/

That is, if you really want a switch on both. What I would do is first switch the shape, create it, and then color it with another switch.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM