HTML SELECT - Change selected option by VALUE usin

2019-01-10 23:53发布

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.

4条回答
beautiful°
2楼-- · 2019-01-11 00:34

If you are using jQuery:

$('#sel').val('bike');
查看更多
祖国的老花朵
3楼-- · 2019-01-11 00:43

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

document.getElementById('drpSelectSourceLibrary').value = 'Seven';
查看更多
贪生不怕死
4楼-- · 2019-01-11 00:46

You can select the value using javascript:

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

DEMO

查看更多
Animai°情兽
5楼-- · 2019-01-11 00:52

try out this....

JSFIDDEL DEMO

using javascript

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

using jQuery

$('#sel').val('car');
查看更多
登录 后发表回答