简体   繁体   中英

(Javascript) How to changed a variable value based on selected option in a dropdown list?

I have a dropdown list right here and I have declared a variable (vki)

<html>
<body>
    <form>
        Select your favorite letter!
        <select id="Fletter">
            <option selected disabled>Choose one</option>
            <option>A</option>
            <option>B</option>
            <option>C</option>
            <option>D</option>
            <option>E</option>
            <option>F</option>
        </select>
    </form>
    <script>
        var vki,
    </script>
</body>
</html>

I want (vki) to have different values when different option is selected. For example, vki=5 when A is selected, vki=7 when B is selected, how would I do that?

Thank you!

Use an object to map the option values to the values you want to put in vki .

$("Fletter").change(function() {
    var vki_map = {
        A: 5,
        B: 7,
        ...
    }
    vki = vki_map[$(this).val()];
});

But I wonder why you don't just put these values in the <option> directly, eg

<option value="5">A</option>
<option value="7">B</option>
...

Then you could do:

vki = parseInt($(this).val, 10);

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