So far I haven’t figured out where is the user’s caret when entering an HTML page with multiple fields.
With the following code (placed right before the closing HTML tag), the page will load and focus the first text or text area field on the page.
<script>
for(i=0; i<document.forms[0].elements.length; i++) {
felement = document.forms[0].elements[i];
if (felement.type == 'text' || felement.type == 'textarea') {
felement.focus(); break;
}
}
</script>
The beauty of the code is that it won’t matter the name of the form or field, giving enough flexibility to use the same JavaScript code on all the pages that have fields in your application.
Notes:
- Different types of fields can be used to receive focus changing the if condition.
- Change the form’s index to the one containing the field that should receive the focus, it currently checks the fields on the first form (index starting at 0).
January 22nd, 2007
If you’re working with web applications that use complex forms, you probably know that it becomes useful to split a very long forms on several pages (keeping interim posts on sessions variables) and process all the received data on a single transaction. But what happens when a user clicks on the Back button all the way to the first page or just wants to close the browser’s window?
Maybe you’ve already noticed those sites that warn your before closing the window? Wouldn’t it be useful, and a nice detail for the users, to let them know when something is about to get ruined because of a wrong click?
While looking for a way to implement this, I came up with onunload event but it didn’t solve the problem since the code would be executed after the user left the page. With a further research, I found that this can achieved using the onbeforeunload event from JavaScript.
On this simple example, the user is warned every time the the page is about to be changed, or the browser’s window closed (the example itself is a bit annoying). You might want to change it’s behavior so that when the proper button (or link) is pressed, the transition to the next page happens without the message (using page variables).
<script language="JavaScript">
window.onbeforeunload = confirmExit;
function confirmExit() {
return "You are about to leave this page. Any changes
made will be lost if your don't press Save.
Are you sure you want to exit this page?";
}
</script>
July 11th, 2006