开发者

How do I use JavaScript in my <select> options list?

How do I use

          <select>
          <option>numbers1-100</option>
          </select>

I have to use 1 to 100 numbers in my option list.Typing all the options takes time and makes code bigger.I guess we have to use javascript to make it work using for loop and document write.But I dont know how to put th开发者_运维百科e code in the right way.How do i list the options list using java script? I mean the java script should be beside my label;example

        number : 1-1oo \\ here the options list should be printed

and number can be anywhere but the script should print options list beside the number.How do i make it ? Unable to figure it out.Been trying from an hour or so.


Place this function in your <script> tags or include it within a script. Than call the function, createSelectOption() whenever you need the select box to be created.

Here is how you would have it loaded on page load with just javascript: `

function createSelectOption() {    
    var select_option = '<select>';
    for(i = 1; i <= 100; i++) { 
       select_option += '<option value=' + i + '>' + i + '</option>';
    }
    select_option += '</select>';
    document.getElementById('div').innerHTML = select_option;
}

I have included a jsfiddle demo to show you that it should be working/


You shouldn't really use javascript for this, it would usually be better using a server-side language such as php. You could use a for loop or a while loop to do this quite easily


Here's one way to do this.

http://jsfiddle.net/ryh7k/1/

var selectEle = document.getElementById('mySelect'),
    optionEle = undefined;

for (var i=1;i<=100;i++) {
    optionEle = document.createElement('option');
    optionEle.setAttribute('value', i.toString());
    optionEle.innerText = i.toString();
    selectEle.appendChild(optionEle);
}


Simplest case:

<select>
<script>
for (var i = 1; i < 101; i++) {
document.write('<option value="'+i+'">'+i+'</option>');
}
</script>
</select>

But there are of course problems with this. First, people without JS will not see any options and having a SCRIPT tag inside a SELECT is not that nice either.

<select id="container"></select>
<script>
var s = document.getElementById('container');
var opts = '';
for (var i = 1; i < 101; i++) {
    opts += '<option value="'+i+'">'+i+'</option>';
}
s.innerHTML = opts;
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜