JavaScript set selected on load

February 13, 2006 / Filed under: JavaScript, PHP

"Pre-selecting" form values

HTML select lists, radio buttons, and checkboxes allow you to set an attribute which "pre-selects" a specific value:

selected="selected"

... or:

checked="checked"

Using these attributes, you can set a "preset" value, for the user. In other words, when the user first views the form, certain values may already be selected for them:

Screen shot of an HTML select list

Screen shot of an HTML checkbox

Now, why would anyone want their form values pre-selected?

A few reasons, actually:

  1. The option that is pre-selected could be an option that is typically selected, anyway. So, this could possibly save the user a step.
  2. Having an option pre-selected protects against "user error," in a situation where the user may have forgot to select an option (and tried to submit the form). (Of course, this is pretty "brash," because it assumes the user would have wanted that option, anyway - when, in truth, it might be better to give them an error, showing them which field was left blank - essentially bringing it to their attention.)
  3. Based on other form field inputs, certain values may need to be pre-selected, or "auto-selected," simply because it may match certain criteria.

Example select list: months

Let’s take an example select list, where the user must select a month:

<select id="month">

	<option id="january" value="january">January</option>
	<option id="february" value="february">February</option>
	<option id="march" value="march">March</option>
	<option id="april" value="april">April</option>
	<option id="may" value="may">May</option>
	<option id="june" value="june">June</option>
	<option id="july" value="july">July</option>
	<option id="august" value="august">August</option>
	<option id="september" value="september">September</option>
	<option id="october" value="october">October</option>
	<option id="november" value="november">November</option>
	<option id="december" value="december">December</option>

</select>

Highlight the current month

By default, when the page loads, the first option highlighted, in this select list, will be January, since that’s the first option in the HTML code.

But, what if we’d like to save the user a step, and automatically have the current month highlighted?

Within our HTML, we could simply apply the selected attribute to the current month:

There. Done. Entry finished. Go eat some cake.

Actually, not quite. What if I don’t want to go into the HTML, at the end of every month, and manually change the selected attribute? That would be silly and pointless, when we can have the computer do it for us.

More specifically, we can either have a server-side programming language do it - or we could have JavaScript do it.

Server-side approach

The server-side approach works fine, but it’s a bit more long-winded than JavaScript.

First, we find the current month (I’ll use PHP, for this example):

$month = date("F");

Next, we create an array with each month as a value:

$months_array = array(

	"january",
	"february",
	"march",
	"april",
	"may",
	"june",
	"july",
	"august",
	"september",
	"october",
	"november",
	"december"

);

Next, we loop through our array, and write out the entire select list:

For the current month of February, this code would result in:

This isn’t so bad, I guess - but consider the situation where you’d like to store your select list HTML, and echo it on another part of the page. The above code would not work, in this case, since we echo it immediately.

To solve this problem, we could store the above code in a function or class (but I won’t get into that code, now...).

I’d rather move on to my "preferred approach" for automatically setting the selected attribute: JavaScript.

JavaScript/DOM approach

First, we find the current month:

var months = new Array(12)

months[0] = "january";
months[1] = "february";
months[2] = "march";
months[3] = "april";
months[4] = "may";
months[5] = "june";
months[6] = "july";
months[7] = "august";
months[8] = "september";
months[9] = "october";
months[10] = "november";
months[11] = "december";

var date_now = new Date();
var month_now = date_now.getMonth();

Next, we set the select list to a variable, for easy reference:

var monthList = document.getElementById("month");

Next, we grab the <option> element that correlates with the current month, and we get this by using our array (months), which values match the id attributes of the <option> elements:

var curMonthOption = document.getElementById( months[month_now] );

And finally, we simply change that <option> value’s selected attribute to true:

curMonthOption.selected = true;

That’s it.

Here is an example of a select list, that always shows the current month:

Just make sure you include this code as a result of the page loading initially (onLoad, or whatever you use to capture the load event).

Which approach is better?

Either approach works the same. I prefer the client-side (JavaScript) approach, because it allows more freedom, but it’s entirely up to you.

Comments/Mentions

# David Earle at 9/28/2006 1:38 am cst

Excellent post, here’s my issue:
On my help page there are several topics from which to choose. If a visitor chooses a topic, he is taken to that page.
I would like to have the default value select when the visitor comes back to that (help) page. Since the page is already loaded, the selected="selected" does not work and his last selection remains present in the drop down. Is there an ’onrefresh’ function in Javascript? (I know, I know, I’ll Google it now); or is there a better way still?

# Chris at 5/23/2007 10:32 pm cst

What if you don't have an ID value for the option you want to select? I can get the Select using getElementById and I know the "value" value that I want to select.

Any suggestions?

TIA.

# Matthom at 5/24/2007 5:45 am cst

Chris, I think the <option> element still needs an id attribute, in order to be targeted with JavaScript. In your case, you are targeting the <select> element, but not the actual <option> that you want selected.

I could be wrong, but I think this is the case.

# Bart McLeod at 6/11/2007 7:59 am cst

The current id's don't use MEX CAN or US prefixes in the ID, so there is no way to preset NL province, since it occurs in MEX and CA... (this is, if you want the preset to reflect the entry that was saved as 'NL' by a user).

# Kikaioh at 12/6/2007 10:04 am cst

Thanks a lot man, that really helped with implementing some of the code I was working on. =)

# jason at 4/19/2008 6:32 pm cst

javascript:set_updateStatusFormVisible(true);

# Jay at 11/12/2008 9:05 pm cst

Why do you want to create a month array manually when you can let PHP do it for you?

} ?>

# ARTI at 12/18/2008 11:58 pm cst

It it cool and very nice. This is open comment. Thanks you again.

# TheBrain at 1/29/2009 12:09 pm cst

@#7: that's right, PHP can do this for you...

I preffer the server side, if a user has javascript disabled it would still be always accurate :)

Greetings ;)

# Suren Sarathkumara at 12/19/2009 2:28 am cst

You don't have to set value for the options at all.

  1. Create the month array.
  2. Find the index number for the current month
  3. document.getElementById("monthlist").selectedIndex = CurrentMonthIndex;