JavaScript set selected on load Feb13 '06

"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.

Categories: JavaScript , PHP

Add Feedback (view all)

Leave feedback

Feedback

Input format: The editor controls below will assist with Markdown syntax.

Status

Sub-status

Your info

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 t ... Read more.

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 ... Read more.

Chris, I think the <option> element still needs an id attribute, in order to be targeted with JavaScript. In your c ... Read more.

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, i ... Read more.

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

javascript:set_updateStatusFormVisible(true); ... Read more.

Popular Pages

  1. Fast rounded corners in Photoshop (7424 recent visits)
  2. PHP – passing variables across pages (2558 recent visits)
  3. JavaScript set selected on load (2413 recent visits)
  4. Removing all child nodes from an element (1828 recent visits)
  5. Firefox 3 smart address bar: wildcard search (1755 recent visits)
  6. iPod songs out of order? (1314 recent visits)
  7. Britney - Everytime piano tab (1137 recent visits)
  8. MySQL LEFT JOIN syntax (884 recent visits)
  9. Firefox 3 smart address bar: wildcard search (722 recent visits)
  10. Date difference in MySQL (651 recent visits)

Similar Entries

Stats

2413 unique visits since July 2008

Syndicate

Advertisements