Tuesday, July 26, 2011

Preventing focus of first input field and Calendar widget on page load in Salesforce

Sometimes in salesforce visualforce pages, the first input field on the page will automatically be set to focus on page load. This can be very annoying and confusing to a user, sometimes scrolling the page to the far right, halfway down the page, or opening up the calendar widget over your other content by default. This post is first showing how to remove focus from either a input field or the calendar widget, and second showing how easily replicate the Salesforce calendar widget(not a permanent solution as class names and javascript libraries could change at any point in time).

First to remove focus from a normal input field, you can put in a extra input with a type of hidden, and give it a Id. Then write a short bit of javascript to call that hidden field and set focus to it on page load.

see code below

<input id="hiddenElement" type="hidden" />

<script type="text/javascript">
  window.onload = setFocus
  function setFocus() {
    document.getElementById("hiddenElement").focus();
  }
</script>


Now that solution works great for a normal text box at the top of the page, and removes the focus every time. However, with that solution I found that if the first input field on the page I was attempting to remove focus from was a calendar widget, it would break the calendar widget. Most likely because it is stepping on a predefined salesforce javascript function of 'window.onload'. So to still remove focus from the calendar widget input and keep it functional, I read a post on the boards at developerforce.com, that provided me with the following solution.

//Towards the top of your page call this script statement.
<script>
function setFocusOnLoad() {}
</script>

How this works was a little unclear, except that it overrides a salesforce library script, and the probably won't work forever disclaimer as always.


Finally as a bonus if you ever need to use the Salesforce calendar widget at your own discretion, as opposed to only with a visual force inputfield component on a SObject field with the correct Date datatype, you can use the following markup.

<span class="dateInput dateOnlyInput">
    <input value="{!someValue}" id="uniqueIdGoesHere" name"sameUniqueId"
          onfocus="DatePicker.pickDate(false, 'sameUniqueId', false);" size="12" type="text />
</span>

This displays a small date time format like this DD/MM/YY, to display the full year and time stamp as well, change the second false in the 'onfocus' call to true. Here is a link to a demo of the calendar widget with both formats.


No comments:

Post a Comment