Use an attribute selector:
var selector = dataVar.split(',').map(function(el) {
return 'option[value='+el.trim()+']';
}).join(',');
$(selector).appendTo('#selected_cats');
Pergunta
I need to move certain <option>
elements from one <select>
list to the other - and perhaps back and forth as well - so it can't rely on hard-coded data and I need to target the <option>
elements I want to move via their value
attribute.
So say I have this html:
<option value="1">cat #1</option>
<option value="2">cat #2</option>
<option value="3">cat #3</option>
<option value="4">cat #4</option>
<option value="5">cat #5</option>
<option value="6">cat #6</option>
Then say I want the elements with the values 3,4,5
how can I do this?
Edit: It would be ideal if I could pass the values wanted in as above such as 3,4,5
.
Edit 2: These values also need to be removed from the select list they are taken from.
After I get the data back I will be appending it to another select list such as:
$(dataVar).appendTo('#selected_cats');
Solução
Use an attribute selector:
var selector = dataVar.split(',').map(function(el) {
return 'option[value='+el.trim()+']';
}).join(',');
$(selector).appendTo('#selected_cats');
Outras dicas
What I did was this..
var data_holder = '';
$.each(mr_val, function(index, number) {
data_holder += '#all_cats option[value="' + number + '"], ';
});
// Ge rid of last space & comma
data_holder = rtrim(data_holder, ' ,');
// Now remove options from first select and append to the other
var options = $(data_holder).appendTo('#selected_cats');
Something like this...?
function moveOptions(sourceList, targetList, movableValues) {
sourceList.find('option').each(function(){
if (movableValues.indexOf($(this).val()) > -1) {
$(this).appendTo(targetList);
}
});
}
// Usage:
var pullFrom = $("#list1");
var moveTo = $("#list2");
var moveThese = ['3','4','5'];
moveOptions( pullFrom, moveTo, moveThese );