I want this javascript to create options from 12 to 100 in a select with id=\"mainSelect\", because I do not want to create all of the option tags manually. Can you give me
Here you go:
for ( i = 12; i <= 100; i += 1 ) {
option = document.createElement( 'option' );
option.value = option.text = i;
select.add( option );
}
Live demo: http://jsfiddle.net/mwPb5/
Update: Since you want to reuse this code, here's the function for it:
function initDropdownList( id, min, max ) {
var select, i, option;
select = document.getElementById( id );
for ( i = min; i <= max; i += 1 ) {
option = document.createElement( 'option' );
option.value = option.text = i;
select.add( option );
}
}
Usage:
initDropdownList( 'mainSelect', 12, 100 );
Live demo: http://jsfiddle.net/mwPb5/1/
See: What is the best way to add options to a select from an array with jQuery?
$('#mySelect')
.append($('<option>', { value : key })
.text(value));
When you create a new Option
object, there are two parameters to pass: The first is the text you want to
appear in the list, and the second the value to be assigned to the option.
var myNewOption = new Option("TheText", "TheValue");
You then simply assign this Option
object to an empty array element, for example:
document.theForm.theSelectObject.options[0] = myNewOption;