How to choose select option with javascript? [duplicate]

六月ゝ 毕业季﹏ 提交于 2021-02-11 15:28:59

问题


I have a html select option

<select id="level" name="level" class="ui dropdown">
   <option value="">Choose</option>
   <option value="1">Abc</option>
   <option value="2">Def</option>
   <option value="3">ghk</option>
</select>

When i load this HTML, i need to choose option (based on data given from DB).

$(document).ready(function(e) {
    var selectedIndex=3; //This data i get from DB
    //now i need to select option in select.

});

So how to assign selected to option based on value?

Running example: http://jsfiddle.net/o850tw9L/


回答1:


Using jQuery you can select option, see below code

$(document).ready(function(e) {
    var selectedIndex=3; //This data i get from DB
    //now i need to select option in select.
    $('#level').val(selectedIndex);
});

JSFIddle Demo with jQuery

JSFiddle Demo with Javascript




回答2:


Try this..

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

<select id="sel">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

Demo:http://js.do/code/73755




回答3:


In pure JS you can do it like this:

var element = document.getElementById('level');
element.value = selectedIndex;

Hope this helps!




回答4:


You can do it with jquery like this,

$(document).ready(function (e) {
    $("#level").val("3");
});

using javascript,

document.getElementById('level').value="3";

Fiddle




回答5:


Like this (JSFiddle):

<select id="level" name="level" class="ui dropdown">
   <option value="">Choose</option>
   <option value="1">Abc</option>
   <option value="2">Def</option>
   <option value="3">ghk</option>
</select>

And script:

$(document).ready(function(e) {
    var selectedIndex=3; //This data i get from DB
    //now i need to select option in select.
    document.getElementById('level').value=selectedIndex;


});



回答6:


See this Question: HTML SELECT - Change selected option by VALUE using JavaScript

I also wrote an example with your code:

document.getElementById('level').value = 2;
<select id="level" name="level" class="ui dropdown">
   <option value="">Choose</option>
   <option value="1">Abc</option>
   <option value="2">Def</option>
   <option value="3">ghk</option>
</select>



回答7:


You can use val() to choose an option of a select by its value property:

$('#level').val('3');

Alternatively, if you prefer to do it by selectedIndex, as your variable name suggests, you can use the eq() method:

$('#level option:eq(3)').prop('selected', true);

Updated fiddle



来源:https://stackoverflow.com/questions/33774858/how-to-choose-select-option-with-javascript

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