简体   繁体   中英

how to change value from select dropdown with just classname in javascript

how do i change value from a select down, when there is just a class name ? lik this one?

<select class="listbox">
<option value="10">10</option>
<option value="20">20</option>
</select>

i need to set the value from 10 to 20 can some one plese help and explain? Thanks

jQuery example:

$('.listbox').val('20')

Or could be easily rewritten to pure JS:

document.getElementsByClassName('listbox')[0].value = '20'

If you need to do it more then once, you could create a clean routine

<script>

    function changeVal(oldval, newval)
    {
        var options = document.getElementsByClassName('listbox')[0].options;
            for (var i=0; i<options.length; i++)
            {
                if (options[i].value == oldval)
                {
                    options[i].value = newval;
                }
                // Just for test
                console.log(i+'|'+options[i].value);
            }
    }

</script>

<select class="listbox">
    <option value="10">10</option>
    <option value="20">20</option>
</select>
<br>
<a href="#"onclick="changeVal(10, 20)">change</a>

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