jeremy
jeremy

Reputation: 653

create an html select via jquery with a while statement or similar

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

Answers (2)

Mike Thomsen
Mike Thomsen

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

Steve Elliott
Steve Elliott

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

Related Questions