开发者

How to store the contents of select box to a variable?

I have a <select> field on my HTML page that is populated with a few options. 开发者_JAVA技巧With the help of AJAX, I replace those options in the select field with more appropriate options.

How can I store the options of my select field into a variable and then load it into the select again? It would be helpful to be able to get back the default options of the select field in some cases.


var $default_opts = $('#mySelect').children();

I used jQuery's .children() here to keep it a little more generic in case you're using <optgroup> elements.

When it comes time to revert to the originals, you could do something like this:

$('#mySelect').empty().append( $default_opts.clone() );

This empties the <select> of its current content, and appends a clone of the defaults so that your copy is retained in its original state.


If you want to restore the objects instead of the html()-string, you can use detach()

//remove options from select and hold them inside a variable
var defaults=$('select option').detach();

//clear select and restore the defaults
$('select').empty().append(defaults);

An example how to use it with replaceWith() :

<select id="target" size="3">
 <option>a
 <option>b
</select>
<input type="button" 
   value="replace"
   onclick="fx($('#target'),this)"
   />

<script  type='text/javascript'>
function fx(o,b)
{
 if(b.value==='replace')
 {
  o.data('defaults',$('option',o).replaceWith('<option>1</option><option>2</option>'));
  $(b).val('restore');
 }
 else
 {
  $(o).empty().append($(o).data('defaults'));
  $(b).val('replace');
 }
}
</script>

http://jsfiddle.net/doktormolle/Sgn72/


My way would be using the jQuery's .data function to store the options html.

select_box = $("#select-box");
select_box.data("orginal_options", select_box.html());
select_box.html("<option value='1'>New Option</option>");

To resotre:

select_box.html(select_box.data("original_options"));

Of course these are the basic ideas, as I don't really know how's your logic. (And please correct me if I'm wrong).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜