jquery remove selected element and append to another
- by KnockKnockWhosThere
I'm trying to re-append a "removed option" to the appropriate select option menu.
I have three select boxes: "Categories", "Variables", and "Target". "Categories" is a chained select, so when the user selects an option from it, the "Variables" select box is populated with options specific to the selected categories option. When the user chooses an option from the "Variables" select box, it's appended to the "Target" select box. I have a "remove selected" feature so that if a user "removes" a selected element from the "Target" select box, it's removed from "Target" and put back into the pool of "Variables" options. The problem I'm having is that it appends the option to the "Variables" items indiscriminately. That is, if the selected category is "Age" the "Variables" options all have a class of "age". But, if the removed option is an "income" item, it will display in the "Age Variables" option list.
Here's the HTML markup:
<select multiple="" id="categories" name="categories[]">
<option class="category" value="income">income</option>
<option class="category" value="gender">gender</option>
<option class="category" value="age">age</option>
</select>
<select multiple="multiple" id="variables" name="variables[]">
<option class="income" value="10">$90,000 - $99,999</option>
<option class="income" value="11">$100,000 - $124,999</option>
<option class="income" value="12">$125,000 - $149,999</option>
<option class="income" value="13">Greater than $149,999</option>
<option class="gender" value="14">Male</option>
<option class="gender" value="15">Female</option>
<option class="gender" value="16">Ungendered</option>
<option class="age" value="17">Ages 18-24</option>
<option class="age" value="18">Ages 25-34</option>
<option class="age" value="19">Ages 35-44</option>
</select>
<select height="60" multiple="multiple" id="target" name="target[]">
</select>
And, here's the js:
/* This determines what options are display in the "Variables" select box */
var cat = $('#categories');
var el = $('#variables');
$('#categories option').click(function() {
var class = $(this).val();
$('#variables option').each(function() {
if($(this).hasClass(class)) {
$(this).show();
} else {
$(this).hide();
}
});
});
/* This adds the option to the target select box if the user clicks "add" */
$('#add').click(function() {
return !$('#variables option:selected').appendTo('#target');
});
/* This is the remove function in its current form, but doesn't append correctly */
$('#remove').click(function() {
$('#target option:selected').each(function() {
var class = $(this).attr('class');
if($('#variables option').hasClass(class)) {
$(this).appendTo('#variables');
sortList('variables');
}
});
});