jsldnppl
jsldnppl

Reputation: 913

How can I move a select element's values & text to another select element

I want to get the <option> values and text from a <select> element #myselect, and add it to another <select> element #newselect. The value and text passed to the second select element, #newselect, must also be disabled. I'd like support for IE 8+.

<select id="myselect">
    <option value="1">Red</option>
    <option value="2">Orange</option>
    <option value="3">Yellow</option>
</select> 

Take the above, disable them and add them to the below:

<select id="newselect">
    <option value="1">Green</option>
    <option value="2">Blue</option>
    <option disabled value="1">Red</option>
    <option disabled value="2">Orange</option>
    <option disabled value="3">Yellow</option>
</select> 

Upvotes: 1

Views: 61

Answers (2)

dfsq
dfsq

Reputation: 193291

You already have jQuery answer. So now if you are curious how it can be in pure javascript, here it is. As you can see, it's a little more verbose of course:

var mySelect  = document.getElementById('myselect'),
    newSelect = document.getElementById('newselect');

while (mySelect.options.length) {
    mySelect.options[0].disabled = true;
    newSelect.add(mySelect.options[0]);
}
<select id="myselect">
    <option value="1">Red</option>
    <option value="2">Orange</option>
    <option value="3">Yellow</option>
</select> 

<select id="newselect">
    <option value="1">Green</option>
    <option value="2">Blue</option>
</select> 

Upvotes: 1

Paul Roub
Paul Roub

Reputation: 36448

Since you included the jQuery tag, here's a jQuery solution.

As long as you're using jQuery 1.x, IE8 support is included.

$('#myselect option').each(
  function() {
    $(this).prop('disabled', true).appendTo('#newselect');
  }
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="myselect">
    <option value="1">Red</option>
    <option value="2">Orange</option>
    <option value="3">Yellow</option>
</select> 

<select id="newselect">
    <option value="1">Green</option>
    <option value="2">Blue</option>
</select> 

Upvotes: 3

Related Questions