Select in jQuery

  • How to get a value:
$('#select').val();
// or
$('select[name=foo]').val();

If selector returns more than one value then .val() will return an array of values.

  • How to get a text value of selected option:
$('#select option:selected').text();
// or
$('#select option:selected').html();
  • How to get an amount value of options inside the ‘#select’ element:
$('#select option').size();
  • How many options were selected:
$('#select option:selected').size();
  • How to select the first one option:
$('#select option:first').prop('selected', true);
  • How to select the last one option:
$('#select option:last').prop('selected', true);
  • How to select an option with value like 3
$('#select option[value=3]').prop('selected', true);
  • How to select an option with text value like ‘apple’:
$('#select option:contains("apple")').prop('selected', true);
  • How to choose the entire options:
$('#select option').prop('selected', true);
  • How to dismiss a selection:
$('#select option').prop('selected', false);
  • How to disable an option and make it available again:
$('#select').prop('disabled', true);
// and backwards
$('#select').prop('disabled', false);
  • How to add an option to the ‘#select’ element at the beginning and at the end:
// begin
$('#select').prepend('new option');
// end
$('#select').append('new option');
  • How to add an option to the ‘#select’ element before and after an option with value like 3:
// before
$('#select option[value=3]').before('new option');
// after
$('#select option[value=2]').after('new option');
  • How to add an option to the ‘#select’ element before and after an option with text value like ‘apple’
// before
$('#select option:contains("apple")').before('new option');
// after
$('#select option:contains("apple")').after('new option');
  • How to add an option before and after a group of similar options:
// before group "cars"
$('#select optgroup[label=cars]').prepend('<option value="">new option</option>');

// after group "cars"
$('#select optgroup[label=cars]').append('<option value="">new option</option>');
  • How to add an option inside the select element based onthe defined array:
var array = {1: 'grape', 2: 'apple', 3: 'orange'};

$.each(array, function(key, value) {
    $('#select').append('<option value="' + key + '">' + value + '</option>');
});
  • How to delete a chosen option:
$('#select option:selected').remove();
  • How to delete the first one or the last one option:
$('#select option:first').remove();
// or
$('#select option:last').remove();
  • How to delete an option with value like 3:
$('#select option[value=3]').remove();
  • How to delete an option with text value like ‘apple’
$('#select option:contains("apple")').remove();
  • How to clear the whole ‘#select’ element:
$('#select').empty();
// or
$('#select option').remove();