HTML选择-使用JavaScript按值改变选择选项

时间:2022-02-22 02:06:54

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

我正在创建一个更新配置文件页面,其中从数据库检索用户配置文件,并显示带有这些值的表单。当涉及到SELECTdropdown时,有许多选项。所以,它冗长的测试所有的值

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.

因此,我想要从它的值中选择相应的选项。比如当我做一些像sel这样的事情的时候。使用JavaScript的value = 'bike'选项2应该被选中。

4 个解决方案

#1


88  

You can select the value using javascript:

您可以使用javascript选择值:

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

DEMO

演示

#2


34  

If you are using jQuery:

如果您正在使用jQuery:

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

#3


8  

try out this....

尝试这个....

JSFIDDEL DEMO

JSFIDDEL演示

using javascript

使用javascript

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

using jQuery

使用jQuery

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

#4


1  

Refer this to see how to it in many different ways: http://javascriptstutorial.com/blog/selecting-dropdown-element-using-javascript-or-jquery/

请参考这篇文章,以多种不同的方式了解它:http://javascriptstutorial.com/blog/select-dropdownelement - use -javascript- jquery/

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

#1


88  

You can select the value using javascript:

您可以使用javascript选择值:

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

DEMO

演示

#2


34  

If you are using jQuery:

如果您正在使用jQuery:

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

#3


8  

try out this....

尝试这个....

JSFIDDEL DEMO

JSFIDDEL演示

using javascript

使用javascript

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

using jQuery

使用jQuery

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

#4


1  

Refer this to see how to it in many different ways: http://javascriptstutorial.com/blog/selecting-dropdown-element-using-javascript-or-jquery/

请参考这篇文章,以多种不同的方式了解它:http://javascriptstutorial.com/blog/select-dropdownelement - use -javascript- jquery/

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