简体   繁体   English

HTML SELECT - 使用JavaScript更改VALUE选定的选项

[英]HTML SELECT - Change selected option by VALUE using JavaScript

There can be many options in a SELECT dropdown. SELECT下拉列表中可以有许多选项。

<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 SELECT dropdown, there are many options. SELECT下拉菜单中,有很多选项。 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. 就像我使用JavaScript做sel.value = 'bike'这样的事情时,应该选择选项2

You can select the value using javascript: 您可以使用javascript选择值:

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

DEMO DEMO

如果你使用jQuery:

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

try out this.... 试试这个....

JSFIDDEL DEMO JSFIDDEL DEMO

using javascript 使用javascript

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

using jQuery 使用jQuery

$('#sel').val('car');
document.getElementById('drpSelectSourceLibrary').value = 'Seven';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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