0

Is it possible to use javascript to modify a select option and add another line of option?

Like this:

<select>
    <option value ="1">1</option>
    <option value ="2">2</option>
    <option value ="3">3</option>
</select>

into this :

<select>
    <option value ="1">1</option>
    <option value ="2">2</option>
    <option value ="3">3</option>
    <option value ="4">4</option>
    <option value ="5">5</option>
</select>

If it is possible to do so, can someone tell me how?

pnuts
  • 58,317
  • 11
  • 87
  • 139
kaloris555
  • 57
  • 1
  • 1
  • 6
  • 2
    Possible duplicate of [Adding options to select with javascript](http://stackoverflow.com/questions/8674618/adding-options-to-select-with-javascript) – mplungjan Nov 02 '15 at 15:15

4 Answers4

1
select = document.getElementById('selectElementId');    
var opt = document.createElement('option');
opt.value = 4;
opt.innerHTML = 4;
select.appendChild(opt);

You can do it in a loop as well:

http://jsfiddle.net/wdmz3cdv/

var min = 4,
    max = 5,
    select = document.getElementById('selectElementId');

for (var i = min; i<=max; i++){
    var opt = document.createElement('option');
    opt.value = i;
    opt.innerHTML = i;
    select.appendChild(opt);
}
prograhammer
  • 20,132
  • 13
  • 91
  • 118
1

In jquery you can do like this...

$('#selectID').append($('<option>', {
    value: 1,
    text: 'New Option' }));

and in javascript you can do like this..

var x = document.getElementById("selectId");
    var option = document.createElement("option");
    option.text = "New Option";
    option.value = "Your Value";
    x.add(option);
Anand Singh
  • 2,343
  • 1
  • 22
  • 34
0
  1. give the select an ID
  2. use JavaScript

One way is like this:

var sel = document.getElementById("mySel");
sel.options[sel.options.length]=new Option(4,4); //adds <option value="4">4</option> to end
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

You can write something like:

var option = document.createElement("option");
option.text = "Text";
option.value = "myvalue";
var select = document.getElementById("id-to-my-select-box");
select.appendChild(option);

Source

Community
  • 1
  • 1
bdanos
  • 141
  • 9