jeudi 25 novembre 2021

Javascript switch on html select option

I've been trying to create script that will make an action, for example write something in a "p" tag. I have 2 select lists in html. I want to have everything with everything interaction, so every element from the first list has different interaction with every element in the second one. I think that using switch will be most efficient method, but can't make it work

<select name="metric" id="metric">
                    <option value="kilometers">km</option>
                    <option value="meters">m</option>
                    <option value="centimeters">cm</option>
                    <option value="milimeters">mm</option>
                </select>
                
                <select name="imperial" id="imperial">
                    <option value="miles">mi</option>
                    <option value="yards">yd</option>
                    <option value="feet">ft</option>
                    <option value="inches">in</option>
                </select>
                
                <button onclick="press()">Click</button>
                <p id="aaa1">Placeholder</p>
var x = document.getElementById("imperial");
var i = x.selectedIndex;


function press() {
    
    if (document.getElementById("metric").getElementsByTagName("option")[0].selected) {
        
        switch (i); {
            case 0:
                document.getElementById("aaa1").innerHTML = "0";
                break;
            case 1:
                document.getElementById("aaa1").innerHTML = "1";
                break;
            case 2:
                document.getElementById("aaa1").innerHTML = "2";
                break;
            case 3:
                document.getElementById("aaa1").innerHTML = "3";
                break;
            default:
                document.getElementById("aaa1").innerHTML = "default";
        }
        
    }
}

After that I would have another if with ("option")[1] etc. Can someone help?

Aucun commentaire:

Enregistrer un commentaire