Alberto Miola
Alberto Miola

Reputation: 4751

Javascript for loop in a select box

I have a webpage with a form that contains some input fields and one of these is a listbox. Inside this listbox I have to add (in crescent order) numbers that go from 40000 to 99999 and they increase by 1000 every time.

Example: 40000 - 41000 - 42000 - 43000 ... 97000 - 98000 - 99000 - 99999

I wrote a Javascript function but it's not working. Here you can see the HTML code:

<fieldset style="width:500px;">
<legend><font color="#D8D8D8"><b>Required Fields</b></font></legend>
<font color="#FFFFFF"><b>Player's Name</b>:</font> <input type="text" name="nome" />
<font color="#FFFFFF"><b>VRs</b>:</font> <select name="cognome">
</select> <br />
</fieldset>

Here there's the javascript function

<script>
var i=40000

for(i;i<42000;i=i+1000)
{var select = document.getElementById("cognome");
select.options[select.options.length] = new Option(i, i)}
}
</script>

My problem is that any data appear on the listbox. Do you have any suggestions?

Upvotes: 0

Views: 355

Answers (3)

louisbros
louisbros

Reputation: 875

You're using getElementById so you need an id:

<select id="cognome" name="cognome">

Also the syntax error where the parentheses need to match :)

Upvotes: 3

WheretheresaWill
WheretheresaWill

Reputation: 6490

Using the comments above:

  • Adding an id="cognome"

  • Correcting the parens.

There's a JFiddle with it working here:

http://jsfiddle.net/WEd84/

Upvotes: 0

Look at your javascript error console, you misplaced a } instead of a ) , see:

select.options[select.options.length] = new Option(i, i}
                              THIS SHOULD BE A ')'-----^

Also add the id as louisbros comments in other answer..

See working demo

Upvotes: 0

Related Questions