-2

I want to add an option element to my select which has the value provided by the #quantite input. I want that when we click the button the GetValues() function adds the element. I tried this:

<input class="text" id="quantite" type="text" name="quantité" />
<select id="multiSelect" size="5" multiple="multiple">
    <option value="o1">Option 1</option>
    <option value="o2">Option 2</option>
    <option value="o3">Option 3</option>
    <option value="o4">Option 4</option>
    <option value="o5">Option 5</option>
    <option value="o6">Option 6</option>
</select>
<br />
<button id="btnGetValues" onclick="GetValues()">Get Values</button>
function GetValues() {
    // Get select object
    var myList = document.getElementById("multiSelect");

    //Create array to store selected values
    var Selectedelement = $("#quantite").val() ;

    myList.add(Selectedelement);
}
}

I get an error in javascript in mylist.add(Selectedelement);

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
r code
  • 7
  • 4

4 Answers4

2

You can create a new option element and use appendChild() to add it to the select. Try this:

function GetValues() {
    var myList = document.getElementById("multiSelect");
    var option = document.createElement('option');
    option.value = document.getElementById('quantite').value;
    option.innerText = 'New Option';
    myList.appendChild(option);
}

Example fiddle

Or for a purely jQuery solution:

<button id="btnGetValues">Get Values</button>
$('#btnGetValues').click(function() {
    $('#multiSelect').append('<option value="' + $('#quantite').val() + '">New option</option>');
});

Example fiddle

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

document.getElementById returns DOM element. You should use jQuery object. And you should also use append instead of add to add new element. Try following.

function GetValues() {
     var myList = $("#multiSelect");
     var Selectedelement = $("#quantite").val();

     myList.append('<option value='+Selectedelement+'>'+ Selectedelement +'</option>');                
}
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
0

You need yo append an option:

$("#multiSelect").append('<option value="anyValue"> '+$("#quantiCommande").val()+' </option>');
void
  • 36,090
  • 8
  • 62
  • 107
0

I prefer plain javascript.

Look this example, I create node element throw createElement API and setting OptionElement attributes.

Davide Ungari
  • 1,920
  • 1
  • 13
  • 24