如何从select中删除和恢复选项?

时间:2013-12-04 12:42:50

标签: javascript jquery html

<select id="first">
    <option value="aaa">asdf</option>
    <option value="bbb">sdf</option>
    <option value="ccc">gfd</option>
    <option value="dd2">fdg</option>
</select>
<button id="delete">delete</button>
<select id="second" style="display: none">
    <option value="aaa">asdf</option>
    <option value="bbb">sdf</option>
    <option value="ccc">gfd</option>
    <option value="dd2">fdg</option>
</select>
<button id="restore">restore</button>

$('#delete').click(function(){
    $('#first option').remove();
})

$('#restore').click(function(){
    //how to restore option for #first?
})

我想从select中删除选项,然后恢复与start相同的选项。我创建了这个辅助选择(#second)。

LIVE DEMO

2 个答案:

答案 0 :(得分:2)

怎么样?
<select id="first">
    <option value="aaa">asdf</option>
    <option value="bbb">sdf</option>
    <option value="ccc">gfd</option>
    <option value="dd2">fdg</option>
</select>
<button id="delete">delete</button>
<select id="second" style="display: none">
</select>
<button id="restore">restore</button>

$('#delete').click(function(){
    $('#first option').appendTo("#second");
})

$('#restore').click(function(){
    $('#second option').appendTo("#first");
})

Demo

答案 1 :(得分:0)

您可以使用append返回值

$('#delete').click(function(){
$('#first option').remove();
})

$('#restore').click(function(){
//how to restore option for #first?
$('#first').append('<option value="aaa">asdf</option><option value="bbb">sdf</option>   <option value="ccc">gfd</option><option value="dd2">fdg</option>');
})