interviews.dotnetthread.com

↑ Grab this Headline Animator

Monday, November 3, 2008

How to set default button in HTML form using Javascript if we have multiple submit buttons in a single form to handle Enter key functionality

HTML with HTML controls:Say we have a form as below with two submit buttons each corresponding to separate inputs.
In this case use two separate Div tags and handle "onkeypress" event of Div tag, call Javascript function by passing event and button to be fired, where we will handle "Enter Key" and fire default button as shown below.




Script:




<script language="javascript" type="text/javascript">
var __defaultFired = false;
function WebForm_FireDefaultButton(event, target)
{alert(target);
var element = event.target event.srcElement;
if (!__defaultFired && event.keyCode == 13 && !(element && (element.tagName.toLowerCase() == "textarea")))
{
var defaultButton;
defaultButton = document.getElementById(target);
if (defaultButton && typeof(defaultButton.click) != "undefined")
{
__defaultFired = true;
defaultButton.click();
event.cancelBubble = true;
if (event.stopPropagation) event.stopPropagation();
return false;
}
}
return true;
}
</script>





HTML code:



<form id="form2" action="#">
<div id="divZipcode2" onkeypress="Javascript:return WebForm_FireDefaultButton(event, 'Submit1')">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td colspan="2">
Block1
</td>
</tr>
<tr>
<td>
<input type="text" id="text1" value="Text1" />
</td>
<td>
<input type="submit" value="Submit1" id="Submit1" onclick="alert('Submit1 Fired.');" />
</td>
</tr>
</table>
</div>
<div id="div1" onkeypress="Javascript:return WebForm_FireDefaultButton(event, 'Submit2')">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td colspan="2">
Panel2
</td>
</tr>
<tr>
<td>
<input type="text" id="text2" value="Text2" />
</td>
<td>
<input type="submit" value="Submit2" id="Submit2" onclick="alert('Submit2 Fired.');" />
</td>
</tr>
</table>
</div>
</form>

Submit this story to DotNetKicks

No comments:

Post a Comment

Post your comments/questions/feedback for this Article.

 

Latest Articles