0

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.

Kyo
  • 974
  • 5
  • 10
user3124690
  • 413
  • 1
  • 12
  • 25

3 Answers3

0

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/

Taleeb
  • 1,888
  • 18
  • 25
0

You could also set a selected attribute on the corresponding option tag as you create the select dynamically.

fray88
  • 820
  • 1
  • 7
  • 23
0

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.

Community
  • 1
  • 1
The Alpha
  • 143,660
  • 29
  • 287
  • 307