Reputation: 83
I am trying to move selected options in select1 to select2 on the click
of a button. This is my HTML code:
<p>
<select id="select1" size="10" style="width: 25%" multiple>
<option value="purple">Purple</option>
<option value="black">Black</option>
<option value="orange">Orange</option>
<option value="pink">Pink</option>
<option value="grey">Grey</option>
</select>
</p>
<button type="button" click.delegate="trig()">Add</button>
<p>
<select id="select2" size="10" style="width: 25%" multiple>
<option value="white">White</option>
<option value="red">Red</option>
<option value="yellow">Yellow</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
</p>
And here is my JS code Containing the button
export class App {
constructor() {
}
trig() {
}
}
What would I have to put in trig()
so that on click the button will move selected items to another list?
Upvotes: 3
Views: 213
Reputation: 868
I have added add
button as per your use case.
Please refer below link and I have updated the solution. I guess your are looking for somewhat same.
If you required more help, please comment on this.
Upvotes: 3
Reputation: 35253
You could loop through the selectedColors1
and get the index
of each selected item. Then push them to color2
array and remove them from the colors
array one by one.
Demo: CodeSandbox
export class App {
colors1 = [
{ id: "purple", name: "Purple" },
{ id: "black", name: "Black" },
{ id: "orange", name: "Orange" }
];
colors2 = [
{ id: "white", name: "White" },
{ id: "red", name: "Red" },
{ id: "blue", name: "Blue" }
];
selectedColors1 = [];
selectedColors2 = [];
add() {
this.selectedColors1.forEach(selected => {
// get the index of selected item
const index = this.colors1.findIndex(c => c.id === selected);
this.colors2.push(this.colors1[index]); // add the object to colors2
this.colors1.splice(index, 1); // remove from colors1
});
}
}
HTML:
<select multiple value.bind="selectedColors1">
<option repeat.for="color of colors1" model.bind="color.id">
${color.name}
</option>
</select>
<button type="button" click.delegate="add()">Add</button> <br />
<select multiple value.bind="selectedColors2">
<option repeat.for="color of colors2" model.bind="color.id">
${color.name}
</option>
</select>
Upvotes: 3