DropDownList (or) Select

Content:

  1. Clear items from DropDownList
  2. Get selected index from DropDownList
  3. Get selected text from DropDownList
  4. Get selected value from DropDownList
  5. Set DropDownList selected value based on display text
  6. Set DropDownList selected value based on display value

1. Clear items from DropDownList:

$('#ddlRole').empty();

2. Get selected index from DropDownList:

var i = $('#ddlRole option:selected').index();
alert('Selected Index is: ' + i);

3. Get selected text from DropDownList:

var roleName = $('#ddlRole option:selected').text();
alert('Selected Role Name is: ' + roleName);

4. Get selected value from DropDownList:

Example: (1)

var roleId = $('#ddlRole option:selected').val();
alert('Selected Role Id is: ' + roleId);

Example: (2)

var roleId = $('#ddlRole').val();
alert('Selected Role Id is: ' + roleId);

5. Set DropDownList value based on display text:

// Now set dropdown selected option to 'Admin'.
var selectedText = 'Admin';
$('#ddlRole option').map(function () {
    if ($(this).text() == selectedText) return this;
}).attr('selected', 'selected');

6. Set DropDownList value based on value:

Example: (1)

var selectedValue = '3';
$('#ddlRole option').map(function () {
    if ($(this).val() == selectedValue) return this;
}).attr('selected', 'selected');

Example: (2)

var selectedValue = '3';
$('#ddlRole').val(selectedValue);
  • Updated
    Mar 14, 2015
  • Views
    2,239