Thursday, September 13, 2012

manipulate drop downs in jQuery

  • Get the value from a drop down:
    var foo = $('#bar:selected').val();
     
  • Get the public-facing value from a drop down:
    var foo = $('#bar:selected').text();
     
  • Set a drop down's value:
    $('#bar').val("baz");
     
  • Empty a drop down:
    $('#bar').empty();
     
  • Append a new option to a drop down:
    $('#bar').append($('<option></option>').val("value").html("text"));
     
  • Remove an item from a drop down:
    $('#bar').find("option[value='foo']").remove();
     
  • Loop through the options in a list:
    var areaselect = $(formtablerows[24]).find('select:first');
    $(areaselect).each(function() {
       $('option', this).each(function () {
          alert($(this).text());
       });
    });

Addendum 4/22/2015: I think that all one has to do anymore is var foo = $('#bar').val(); for getting the value from a drop down.

No comments:

Post a Comment