Multiple submit buttons on a .NET page

Posted on Wednesday, December 24, 2008

Since .NET pages can only have one managed <form> element, some problems arise when pressing enter to submit a login request on a page with a search bar and a login form. Since the ASP button controls convert to submit html inputs, the browser can not determine that because the user hit enter after typing in their password in the login form, that the submit button for the login form should be pressed instead of the search button for the search bar. One solution to this problem is to make the search bar using actual html elements instead of ASP controls and then use javascript to grab the search query and put it into a get request made by changing window.location. My solution was to whip up some javascript to determine the correct submit button to press using proximity of the text field that had focus when the enter key was pressed to the submit button using the DOM model of the page. Here is what I came up with:
<script type="javascript">
// SubmitManager
var activeObject = "";
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
function FindSubmitButton(element,down)
{
var found = false;
if(element.hasChildNodes()){
for(var i in element.childNodes){
if(element.childNodes[i].nodeName != undefined){
if(element.childNodes[i].hasChildNodes()){
found = FindSubmitButton(element.childNodes[i], true);
if(found){
break;
}
}
else{
if(element.childNodes[i].type == "submit"){
found = element.childNodes[i];
break;
}
}
}
}
}
if(!down){
if(found == false){
if(element.nodeName != "#document"){
return FindSubmitButton(element.parentNode, false);
}
else{
return null;
}
}
else{
return found;
}
}
else{
return found
}
}
function ManageKeyPress(e)
{
var code;
var allow = true;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
if(code == 13){
allow = false;
var button = FindSubmitButton(activeObject, false);
if(button != null){
button.click();
}
}
return allow;
}

function InitializeManager(){
elements = document.getElementsByTagName("INPUT");
for(var i in elements){
if(elements[i].type == "text"){
elements[i].onfocus = function(){
activeObject = this;
}
elements[i].onkeypress = ManageKeyPress;
}
}
}
addLoadEvent(InitializeManager);
</script>
The SubmitManager can be included right into an existing page without any extra work, but it would probably be best to put the code into a .js file and then include it that way:
<script type="javascript" src="SubmitManager.js"></script>

Comments:

Post a Comment

Subscribe to Post Comments [Atom]





<< Home