Using JavaScript to prevent or trigger form submission when ENTER is hit on textbox

for Preventing:

Suppose there is a textbox control called txtDemo. Add below line of code in the page_load method.

txtDemo.Attributes.Add("onkeypress", "return noenter()");


< script type="text/javascript" >
function noenter() {
return !(window.event && window.event.keyCode == 13); }
< /script >


For Triggering:

Option 1:

Suppose there is a textbox control called txtDemo and a button control namely btnSubmit. Add below lines of code in the page_load method.

txtDemo.Attributes.Add("onkeypress", "return clickButton(event,'" + btnSubmit.ClientID + "')");
btnSubmit.Attributes.Add("onclick", "return validate_Data();");


< script type="text/javascript" >

function clickButton(e, buttonid)
{
var bt = document.getElementById(buttonid);
if (typeof bt == 'object')
{
if (event.keyCode == 13)
{
bt.click();
return false;
}
}
}
< /script >


Option 2:

In case of IE4+

Suppose there is a textbox control called txtDemo. Add below line of code in the page_load method.

txtDemo.Attributes.Add("onkeypress", "return entsub(this.form)");


< script type="text/javascript" >
function noenter() {
return !(window.event && window.event.keyCode == 13); }
< /script >

In Case of Netscape Navigator

txtDemo.Attributes.Add("onkeypress", "return entsub(event,this.form)");


< script type="text/javascript" >
function entsub(event,ourform) {
if (event && event.which == 13)
ourform.submit();
else
return true;}

< /script >

No comments: