Reputation: 653
How do I write an html select statement via jquery?
Let's say I've got this in mind:
<select id="mySelect">
<option value="400">400</option>
<option value="401">401</option>
<option value="402">402</option>
<option value="403">403</option>
</select>
And I need it to be written from jquery.
I've tried this (without success)
$('#div2').append('<select name = "myshield2" id="myshieldSelect2">');
var i = 400;
while (i < '410') {
// do some code
$('#div1').append('<option name="asdf" value = "1">Hey ' + i + ' is the value!</option>');
i++;
}
$('#div2').append('</select>');
Upvotes: 1
Views: 611
Reputation: 37506
$('#div1').append('<option name="asdf" value = "1">Hey ' + i....');
is wrong It should be
$('#myshieldSelect2').append('<option name="asdf" ....');
Completed it is:
$('#div2').append('<select name = "myshield2" id="myshieldSelect2">');
var i = 400;
while (i < '410')
$('#myshieldSelect2').append('<option name="asdf" value = "1">Hey ' + i++ + '...');
Upvotes: 0
Reputation: 659
When using append jQuery appends the actual html elements instead of the html, its not like writing to a stream of HTML.
Also, appending to HTML attached to the document itself in small parts is extremely inefficient. The following variation of your code should work and should be much faster:
var html = [];
html[html.length] = '<select name = "myshield2" id="myshieldSelect2">';
var i = 400;
while (i < '410') {
// do some code
html[html.length] = '<option name="asdf" value = "1">Hey ' + i + ' is the value! </option>';
i++;
}
html[html.length] = '</select>';
$('#div1').append(html.join(''));
Here's an example of it in action: JSBin Example
Upvotes: 1