jQuery, select and options

Here's a couple of snippets that covers some aspects of working with jQuery to manipulate SELECT-elements.

Add options to a SELECT-element with jQuery

<select id="mySelect"></select>

<script language="javascript" type="text/javascript">
var tmp = new Array();

tmp.push("<option value=\"my value\">option #1</option>");
tmp.push("<option value=\"my value 2\">option #2</option>");

$("#mySelect").html(tmp.join(''));

</script>

Getting the selected value

  $('#mySelect').val();
If you have a multiple choice element you should go with this code:
  $('#mySelect option:selected').each(function(i, opt){  
alert($(opt).val());
});

Getting the text of the selected option

  $('#mySelect option:selected').text();
If you have a multiple choice element you should go with this code:
  $('#mySelect option:selected').each(function(i, opt){  
alert($(opt).text());
});

Remove a specified option

This piece of code removes the option that has value=1 from the selectbox.
  $('#mySelect option[value=1]').remove();

Clear a selectbox

  $('#mySelect').html('');

Related posts:

Comments

comments powered by Disqus