Javacadabra
Javacadabra

Reputation: 5758

Use JQuery to set the select option value and text from Array

I have a select box that I am getting multiple values from and storing them in an Arrayusing JQuery.

I would like to know how I can then use the contents of this Array to populate options in another select box.

So currently I've got this:

 $('#addBtn').click(function(e){
        e.preventDefault();
        //Get the selected Items in the dropdown 1
        var selected = new Array();
        $('#compresult option:selected').each(function(){
            selected.push($(this).val() + " " + $(this).text());//Add to Array
        });

        //Update contents of dropdown 2  with the Array 
     });

My HTML for dropdown is :

<select multiple="multiple" name="contributors[]" id="compresult">
    <option value="0"></option>
    <option value="3610">X</option>
    <option value="3605">Y</option>
    <option value="335">Z</option>
 </select>

If I select option X and Y my selected array in my JS Code outputs this:

Array [ "3610 X", "3605 Y" ]

How can I then use these values to populate another dropdown? i'm trying to implement an ADD/REMOVE from list functionality type thing.

EDIT: EXPECTED OUTPUT OF DROPDOWN 2

<select multiple="multiple" name="dropdown2" id="compresult">
        <option value="3610">X</option>
        <option value="3605">Y</option>
</select>

Upvotes: 1

Views: 3309

Answers (3)

Steve
Steve

Reputation: 20459

Just build the html string in your loop:

$('#addBtn').click(function(e){
    e.preventDefault();
    //Get the selected Items in the dropdown 1
    var drop2html = '';
    $('#compresult option:selected').each(function(){
        drop2html += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
    });

    $('#drop2').html(drop2html);
});

Upvotes: 2

Balachandran
Balachandran

Reputation: 9637

ID should be unique id="compresult">

 $('#addBtn').click(function (e) {
    e.preventDefault();

    var selected = $('#compresult option:selected').clone(); // get the selected option and copy that element 
    $("#compresult1").html(selected); // insert into new dropdown list 

});

UPDATED DEMO

Upvotes: 3

Mitya
Mitya

Reputation: 34556

Change the push line to

selected.push([$(this).val(), $(this).text()]);

...so we have the option value and text held separately, not concatenated as one string.

Then, to create the new select (you don't say if you want to create a new one or populate an existing one - I'll assume the latter):

var other_sel = $('#other_select').empty();
$.each(selected, function(i, arr) {
    $('<option /', {value: arr[0], text: arr[1]}).appendTo(other_sel);
});

Upvotes: 0

Related Questions