Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use a for loop in <select> in html? and how?

I am trying to use a for loop in html but i dont even know if this is possible. Is it? and if yes how? I dont want to use php. only html and javascript.

this is my goal: i have a file containing .txt files. i want to count the number of txt files and when i get the number i want to send it to where i will use a for loop to put the txt file's numbers in a dropbox.

Thanks

like image 491
user1438482 Avatar asked Oct 04 '12 10:10

user1438482


2 Answers

Lots of answers.... here is another approach NOT using document.write OR innerHTML OR jQuery....

HTML

<select id="foo"></select>

JS

(function() { // don't leak
    var elm = document.getElementById('foo'), // get the select
        df = document.createDocumentFragment(); // create a document fragment to hold the options while we create them
    for (var i = 1; i <= 42; i++) { // loop, i like 42.
        var option = document.createElement('option'); // create the option element
        option.value = i; // set the value property
        option.appendChild(document.createTextNode("option #" + i)); // set the textContent in a safe way.
        df.appendChild(option); // append the option to the document fragment
    }
    elm.appendChild(df); // append the document fragment to the DOM. this is the better way rather than setting innerHTML a bunch of times (or even once with a long string)
}());

And here is a Fiddle to demo it.

like image 186
rlemon Avatar answered Nov 14 '22 23:11

rlemon


Yes you can for example write this code in html body tag

<select>
<script language="javascript" type="text/javascript"> 

for(var d=1;d<=31;d++)
{
    document.write("<option>"+d+"</option>");
}
</script>
</select>
like image 42
Anuj Avatar answered Nov 14 '22 23:11

Anuj