A textbox that trigger's a button submit when user hits "Enter"

The other day i was developing a Visual Force Page (VF Page) which has a search box and a button to Search on my custom objects. I noticed that if I hit enter the page reloads but the button is not clicked or posted back to the Salesforce server.

Naturally this feature should have been implemented in Salesforce framework but however, i thought maybe i could give it a try myself. After a hour or so of pondering on different directions I came up with a javascript block that catches the Enter key and calls the "click" method of the input button on the page.

However, the javascript alone seems not be working fine and I still had problems when I pressed the Enter key.

Turns out in order to come over this problem I will need to add a hidden textbox! If you have only one textbox in the page you will need to use the following approach as well:





Code:
<apex:inputText id="searchText" size="40" value="{!searchText}" onkeyup="doSearchOnEnter(event)"/>

<apex:inputText style="display:none"/>
<apex:commandButton id="btnSearch" value="Search" action="{!doSearch}" status="status"/>


function doSearchOnEnter(e)
{
var keynum = 0;
if (window.event) {
keynum = window.event.keyCode;
}
else if (e.which) {
keynum = e.which;
}

if (keynum == 13) {
var mySearchButton = FindFormElement("btnSearch","button");
if (mySearchButton != null) mySearchButton.click();
else window.alert("was not found.");
}
return false;
//return true;
}

function FindFormElement(name,type)
{
for(var frm = 0; frm < fld =" 0;" elt =" document.forms[frm].elements[fld];" type ="=">= 0) {
return elt;
}
}
}

return null;
}



Another method by which you can get the reference Id of the Search button in your javascript is to use the following code:

var mySearchButton = document.getElementById("{!$Component.btnSearch}");

therefore, FindFormElement javascript function won't be required anymore.

No comments:

Post a Comment