HTML SELECT - Change selected option by VALUE using JavaScript

核能气质少年 提交于 2019-11-26 15:50:42

问题


There can be many options in a SELECT dropdown.

<select id="sel">
    <option value="car">1</option>
    <option value="bike">2</option>
    <option value="cycle">3</option>
    ...
</select>

I'm creating a Update Profile page where a user's profile is retrieved from the database and a form is shown with those values. When it comes to SELECTdropdown, there are many options. So, its tedious test all values

if (value == '1')
    echo "<option selected value='car'>1</option>";`

So, I want to have the corresponding option selected from its value. Like when I do something like sel.value = 'bike' using JavaScript the option 2 should be selected.


回答1:


You can select the value using javascript:

document.getElementById('sel').value = 'bike';

DEMO




回答2:


If you are using jQuery:

$('#sel').val('bike');



回答3:


try out this....

JSFIDDEL DEMO

using javascript

​document.getElementById('sel').value = 'car';​​​​​​​​​​

using jQuery

$('#sel').val('car');



回答4:


document.getElementById('drpSelectSourceLibrary').value = 'Seven';


来源:https://stackoverflow.com/questions/12265596/html-select-change-selected-option-by-value-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!