8 useful jQuery select box option tricks tips

jQuery select box option tricks tips
jQuery select box option tricks tips

jQuery select box option tricks tips for different select box process. List given with demo/example for play with select element using jQuery.

jQuery select box option tricks tips list:

  • Get option by id, class, data attribute or value
  • Get selectbox selected option value
  • Get selectbox selected option text
  • Get selected option count
  • Remove option from selectbox
  • Add option to selectbox
  • Loop on selectbox option
  • Change option selected status

Let’s start jQuery select box option tricks tips example one by one.

Get option by id, class, data attribute or value

//Get option by id
$('#id-opt3').val();

//Get option by class
$('#class-opt3').val();

//Get option by data attribute
$('#mySelectId option[data-id="data-opt3"]').val();

//Get option by value
$('#mySelectId option[value="val-opt3"]').val();

Get selectbox selected option value

$('#mySelectId option:selected').val();

Get selectbox selected option text

$('#mySelectId option:selected').text();

Get selected option count

$('#mySelectId option:selected').length;

Remove option from selectbox

$('#mySelectId option[value="val-opt4"]').remove();

Add option to selectbox

var optHtml = '<option value="val-opt5">New option</option>';
$('#mySelectId').append(optHtml);

Add option

Loop on selectbox option

$('#mySelectId > option').each(function(){
    alert($(this).text()+' '+$(this).val());
});

Test loop

Change option selected status

//add select
$('#mySelectId option[value="val-opt1"]').prop('selected', true);

//remove select
$('#mySelectId option[value="val-opt1"]').prop('selected', false);