How to select option in dropdown menu using jQuery

Sometimes we need to find the selected option in a select component.

HMTL

<select name=”options” id=”optionsById”>
      <option value=”1″>Red</option>
      <option value=”2″ selected=”1″>Green</option>
      <option value=”3″>Blue</option>
</select>


Javascript

//remove selected one
$(‘option:selected’, ‘select[name=”options”]’).removeAttr(‘selected’);
//Using the value by name
$(‘select[name=”options”]’).find(‘option[value=”3″]’).attr(“selected”,true);
//or
$(‘select[name=”options”]’).find(‘option[value=”3″]’).prop(“selected”,true);
//or
$(‘select[name=”options”]’).val(‘3’);
//Using the value by id
$(‘#optionsById option:eq(“1”)’).prop(“selected”,true);
//Using the text
$(‘select[name=”options”]’).find(‘option:contains(“Blue”)’).attr(“selected”,true);
Advertisements

How to sort an array of objects with javascript

We  can sort an array using this method:

  1. This is the method to sort the array:
    var array = [(name, artist),(name, artist),(name, artist)];
    
    function SortByName(a, b){
      var aName = a.name.toLowerCase();
      var bName = b.name.toLowerCase(); 
      return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
    }
    
    
  2. How to sort the array with data? Just do:
    var arr = [{name:'bob', artist:'rudy'},{name:'johhny', artist:'drusko'},{name:'tiff', artist:'needell'},{name:'top', artist:'gear'}];
    array.sort(SortByName);

Reference link: http://stackoverflow.com/questions/5503900/how-to-sort-an-array-of-objects-with-jquery-or-javascript