Adding A Default To A Select With JQuery

I needed to add a default value to a select. The select was generated in some not so easy to change code (i.e. not my code) but it needed a default. This was the result:

Example (SelectDefault.html):

<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="js/jquery-1.10.2.js"></script>

<select id="aSelect">
  <option value="1">Opt 1</option>
  <option value="2">Opt 2</option>
  <option value="3">Opt 3</option>
  <option value="4">Opt 4</option>

$(function() {
	var sl =  $("#aSelect option:selected");
	if ( sl.length == 0 ) {
		$("#aSelect option[value='3']").attr('selected', 'selected');
	} else if (sl.length == 1) {
		if ( ! sl.get(0).defaultSelected ) { 
			$("#aSelect option[value='3']").attr('selected', 'selected');



A number of things to note.

  1. Some browsers add a default as the first item if one is not specified in the options. This is because the HTML/HTML5 specification says that the behavior is undefined if you don't have a selected item. This is the reason for the goofy check with number of selected equal to 1.
  2. Adding a default like this really makes sense when the default is not the first item. In the actual case that I was working on the default was the current state (AZ, …, WY) that they were in. The problem is that you want the list to be alphabetical, but you need the default to be down the list.
  3. Not all browsers use an automatic default if one is not specified. This is the first case in the if.

•       •       •       •       •       •

Summary: # of Words: 227
Author: Philip Schlump
Published On: 2013-05-05

Download code from this articles in .tar.gz for Mac/Linux/Unix or .zip with CR/LF for Windows format.


Before You Go....

Have you read "Unintend Consinsequences"?

"I laughed so hard it hurt..."
    Rod Brown

"Incredibly funny! Incredibly true!"
    Tad Stevens