“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:
![]()

Now, why would anyone want their form values pre-selected?
A few reasons, actually:
- The option that is pre-selected could be an option that is typically selected, anyway. So, this could possibly save the user a step.
- 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.)
- 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:
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 element that correlates with the current month, and we get this by using our array (
months), which values match the id attributes of the elements:
var curMonthOption = document.getElementById( months[month_now] );
And finally, we simply change that 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:
function function_20060213a () { var month = document.getElementById("20060213a");
var monthNames = new Array(12)
monthNames[0] = "january"; monthNames[1] = "february"; monthNames[2] = "march"; monthNames[3] = "april"; monthNames[4] = "may"; monthNames[5] = "june"; monthNames[6] = "july"; monthNames[7] = "august"; monthNames[8] = "september"; monthNames[9] = "october"; monthNames[10] = "november"; monthNames[11] = "december";
var date_now = new Date(); var month_now = date_now.getMonth();
var curMonthOption = document.getElementById(monthNames[month_now]);
curMonthOption.selected = true; }
addEvent(window, 'load', function_20060213a, false);
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.
My technical meanderings and other nonsense. Published since 2002. No, really. I'm *that* internet-old. I remember the days of
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?
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.
Chris, I think the
<option>element still needs anidattribute, 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.
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).
Thanks a lot man, that really helped with implementing some of the code I was working on. =)
javascript:set_updateStatusFormVisible(true);
Why do you want to create a month array manually when you can let PHP do it for you?
}
?>
It it cool and very nice. This is open comment. Thanks you again.
@#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 ;)
You don’t have to set value for the options at all.
Very useful tutorial, thx for share..
Thank you, after about 1 hour of looking I finally came across your blog. Cheers.
Not to be negative but all of that takes way too many lines. This function I wrote works like a charm. Try it out
function selectdate(){ $datearray=array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"); $monthremoved=date("n"); unset($datearray[$monthremoved]); $datearray = array_values($datearray); $date=date("M"); echo "<select name='month' >"; echo "<option selected='selected' value='".$date."'>".$date."</option>"; for($i=0;$i<11;$i++){ echo "<option value='".$datearray[$i]."'>".$datearray[$i]."</option>"; } echo "</select>"; }Client-side sometimes doesn’t work, and has some latency in being executed, specially when you’ve got a huge HTML document sent to the client. However, I also like the client-side more. Cause I’m a fan of JavaScript.
Thanks.
This code is perfect for my specific need! A lot of you seem to miss that Matt was using the date example as just ONE EXAMPLE for demonstration purposes. We all know there are several ways to code, a polite “here’s how I write my code, what do you think?” is appreciated. What is not appreciated is slamming another programmer’s style of coding especially if the code WORKS.
I plan to use Matt’s logic of inserting id’s to each <option> tag in order for my selections to be set by reading the last users’ selections stored in cookies. I know how to do this using server-side code, but I wanted to know how to do this entirely using client-side code, and Matt’s example is perfect.
Matt, thank you and please continue with the creative coding!
…OPTION tag so I can set the select from the users’ last selection from stored cookies.
Sorry, I accidentally included a tag that caused the rest of the comment to be left off.
Sorry, but I’m getting a lot of errors on this page and the current month is not being selected. It is April 2012 and January is still getting the focus? Maybe a cookie thing? The post date maybe expired. I would like to know how to find out if any select element has an option selected with a value of 1 so that I can disable the form button/fieldset button and write it’s innerHTML (THE BUTTON) as ‘Sold!’ if selected index = 1 and index length = 1 etc.
in the php code you have the array accessed via $admission_array[i].
This should read $admission_array[$i]