0

I'm trying to fill a select list with the values entered in an input text box when the user clicks on a button. For eg:

HTML:

<form>
                <h2>Add EVENT/MARKET/SELECTION ID </h2>
                <select id="id_type">
                        <option value="sEVENT">Event</option>
                        <option value="sEVMKT">Market</option>
                        <option value="sSELCN">Selection</option>
                 </select>

                <input id="entered_id" type="number"/>

              <button id="add_id" onclick="populateList()">Add</button>
</form>
<form>
                <h2>Entered IDs</h2>
                <select id="list_id" size="10" multiple="true"></select>

</form>

JS:

function populateList() {
        var events_id   = document.getElementById('entered_id').value;  
/*I want this events_id to be entered to the select list "list_id"*/
}

I tried $("#list_id").append(events_id) but that didn't work. Any help is appreciated. Thanks

4 Answers 4

3

since its <select> you need to append <option> tag, as:

$("#list_id").append("<option value='"+events_id+"'>"+events_id+"</option>");
Sign up to request clarification or add additional context in comments.

2 Comments

For some reason, the value appears in the select list for a fraction of a second and then disappears. I shall debug it. In the meantime, if you know what could be wrong, please let me know.
Well, it was because my select lists were enclosed in "form"s. It worked fine when I removed the form tag. But what if I want to have it in a form tag??
1

Try FIDDLE

 $("#add_id").click(function () {
      var value = $("#entered_id").val();    
      $("#list_id").append("<option value =" + value + " >" + value + "</option>");
 });

Comments

0

using JavaScript

var option = document.createElement("option");
option.text = document.getElementById('entered_id').value;  
option.value = document.getElementById('entered_id').value;  
var select = document.getElementById("list_id");
select.appendChild(option);

Comments

0

Doing everything the jQuery way you can bind a click handler to the button instead of the inline method.

$('#add_id').click(function() {
  $('<option/>', { text: this.value }).appendTo('#list_id');
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.