Sir
Sir

Reputation: 8280

How to populate a select box with Javascript

I have a simple form with a select box i want to populate with data but i'm not understanding how to do.

This is my form:

<form name="form">    
 <select name="req_one" style="width:250px;"/> </select>    
</form>

This is what i tried in my JS:

var name = 'test';
var i = 1;
document.form.req_one =new Option(name, i);

This should then result in the equivalent :

<option value="1"> Test </option>

What am i doing wrong?

Upvotes: 1

Views: 9542

Answers (4)

mplungjan
mplungjan

Reputation: 177684

Your HTML is invalid, you are closing the select tag

Also wait until the select is available in the DOM

Here is an example

window.addEventListener("load", function() {
  const name = 'test';
  const value = 1;
  const sel = document.querySelector("[name=req_one]"); // or give it an ID and use document.getElementById("req_one")
  if (sel) {
    sel.options[sel.options.length] = new Option(name, value);
  } else {
    alert("Where did the sel go?");
  }
})
<form name="myform">
  <select name="req_one" style="width:250px;"></select>
</form>

Upvotes: 4

Matt Stone
Matt Stone

Reputation: 3890

You're forgetting to add the newly created Option to the select element's list of options:

document.form.req_one.options[0] = new Option(name, i);

JSFiddle example: http://jsfiddle.net/zxT8U/2/

Upvotes: 0

Tarun Kumar
Tarun Kumar

Reputation: 518

I would suggest a easy way with jquery .

var name = 'test';
var i = 1;
$("select[name='req_one']").append('<option value="'+i+'">'+value+'</option>');

I hope you know how to use jquery .

Upvotes: 1

Aashray
Aashray

Reputation: 2753

You made a tiny error. I consolidated your entire code:

<html>
<head>
<script type="text/javascript">
function l1(){
    var name = 'test';
    var i = 1;
    document.form.req_one.options[0] =new Option(name, i);//you forgot to include .options[0]
}
</script>
</head>
<body onload="l1()">
<form name="form">    
 <select name="req_one" style="width:250px;"/> </select>    
</form>
</body>
</html>

Upvotes: 0

Related Questions