简体   繁体   中英

Select the option dynamically using Jquery

I am designing a dynamic HTML for Select Option like below:

item += "<td class='ddl' style='width:40%;'>";
item += "<select>"
item += " <option id='list' name='selector' value=" + select + ">" + select + "</option>";
for (var l = 0; l < array.length; l++) {
    item += " <option class='ddl' value=" + array[l] + ">" + array[l] + "</option>";
}
item += "</select>";
if ("One"!= '') {
    $('#list').val("One");                      
}
item += "</td>";

The above code creates a dynamic HTML like below:

<select disabled="">
<option select="" value="Please" name="selector" id="list">Please Select</option>
<option value="One" class="ddl">One</option> 
<option value="Two" class="ddl">Two</option>
</select>

I want to set the value of the Select to "One" dynamically.

NOTE: The code is not inside document.ready, as I cant keep the code inside ready(). Might be I am assigning the value to the Select before it is revdered on the page. Please suggest me.

You need to call the javaScript to select the value after the dropdown(select) is added to the page. For example if the html is

<div id="myContainer" />

Then the javascript should be like

var item = "";
//Insert your code to create item
item +="<select id='mySelect'>";
item +='<option select="" value="Please" name="selector" id="list">Please   Select</option>';
item +='<option value="One" class="ddl">One</option> ';
item +='<option value="Two" class="ddl">Two</option>';
item +='</select>';

$('#myContainer').append(item); //Add to html

//Now the id "mySelect" is available
$('#mySelect').val('One')

I've added a jsFiddle to demonstrate this at http://jsfiddle.net/taleebanwar/n9vCb/

您还可以在动态创建选择时在相应的选项标签上设置一个所选属性。

If you are using jQuery then why don't you utilize the library for creating the select , for example, using something like this ( Example ):

var numbers = ['one', 'two', 'three', 'four', 'five'];
var select = $('<select/>', {id:'list', name:'selector'});
$.each(numbers, function(key, value) {
    var text = value[0].toUpperCase() + value.substr(1);
    var option = $("<option/>", { class:'ddl', value: value, text: text });
    select.append(option);
});
select.val('two').appendTo('body');

I've appended the select into body but you may append it into a td and you can achieve it, give it a try, create the td same way and insert the select in the td and then insert the td in the table. Also you may check this answer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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