Remove and restore options from select

html, javascript, jquery, php

Solution

Best approach is store a clone of the options on page load. Then clone that clone to restore, so you always keep the first clone as the cache.

var $options=$('#sel option').clone();

function restore(){
 $('#sel').html( $options.clone()) 
}

DEMO

Now if you want to do any filtering of options, can do it on the cache also, you always have the full set stored

$('#filtered').click(function(){
    /* only options with value > 3*/
    var opts=$options.clone().filter(function(){
       return this.value > 3; 
    })
    $('#sel').html(opts)    
})

Problem

I have html: ``` <select id="sel"> <option value="1">aaa</option> <option value="2">bbb</option> <option value="3">ccc</option> <option value="4">ddd</option> <option value="5">eee</option> <option value="6">fff</option> <option value="7">ggg</option> </select> <button id="remove">remove</button> <button id="restore">restore</button> ``` and javascript: ``` function rand(){ return Math.floor(Math.random() * 7) + 1; } function deleteRandom(){ $.each([rand(), rand(), rand()], function( index, value ) { $("#sel option[value=" + value + "]").remove(); //here should be saved... }); } function restore(){ //this function should restore #sel } $("#remove").click(function(){ deleteRandom(); }) $("#restore").click(function(){ restore(); }) ``` LIVE DEMO: http://jsfiddle.net/g4Q8B/ How is the best method for save remove option from select? I dont want use hide, display:none etc, because this not working in all browsers. I dont want also use disabled. I want remove this, and next or previous save all options from select. Maybe i should save all select#sel, but how?

Original source