Reputation: 307
I want to know how to append options from a select box into another select box. But the catch is that I want to append all students that are in the select box without caring if the option is selected or not, if the student is in the select box then they should be appended into the other select box.
Below is the jquery code I have which is suppose to do the appended but is not happening at moment:
var selectedStudents = jQuery("select#studentadd").find("option");
selectedStudents.appendTo($("select#studentexist"));
Below is the select box #studentadd
:
<select multiple="multiple" name="addtextarea" id="studentadd" size="10">
<option value='1'>u08743 - Joe Cann</option>
<option value='4'>u03043 - Jill Sanderson</option>
<option value='7'>u08343 - Craig Moon</option>
</select>
Below is the select box the students should be appended into:
<select id="studentexist" name="existtextarea"></select>
Upvotes: 0
Views: 378
Reputation: 74738
use .clone()
: http://jsbin.com/ucozis/4/edit
$(function(){
$('#studentexist').html($('#studentadd option').clone());
$('#studentadd').html('');
});
just after .append()
or .clone()
blank the select.
As you mentioned your scenario this is the updated answer to that:
$(function(){
$('button').click(function(){
$('#studentexist').html($('#studentadd option').clone());
$('#studentadd').html('');
});
});
and here is the fiddle which replaces all the contents on click of the button http://jsbin.com/ucozis/5/edit
Upvotes: 0
Reputation: 2190
Try this code...
var str="";
$('#studentadd').find('option').each(function(){
str+="<option>"+$(this).html()+"</option>";
});
$('#studentadd').html("");
$('#studentexist').html(str);
Upvotes: 1
Reputation: 5838
you can use jquery
$.html() to do this
var opt = $("#studentadd").html();
$("#studentexist").html(opt);
update:
Use $.detach() to move DOM
var opt = $("#studentadd").detach();
$("#studentexist").html(opt);
Upvotes: 1
Reputation: 146269
You may try this
$("select#studentadd option").each(function(){
$("select#studentexist").append($(this).clone());
});
Update: (instead of copy)
$("select#studentadd option").each(function(){
$("select#studentexist").append($(this));
});
Upvotes: 0
Reputation: 4383
Your code works flawlessy, actually, but it moves the options from the first select to the second. If you wanted to copy them, you would need to add a .clone()
(here for a fiddle):
var selectedStudents = jQuery("select#studentadd").find("option");
selectedStudents.clone().appendTo($("select#studentexist"));
Upvotes: 0
Reputation: 32591
It should work, maybe you forgot this
$(document).ready(function(){
var selectedStudents = jQuery("select#studentadd").find("option");
selectedStudents.appendTo($("select#studentexist"));
});
Upvotes: 1