I have a form with two text boxes, one select drop down and one radio button. When the enter key is pressed, I want to call a javascript function(User defined). But when I press the enter key the form is getting submitted. How do I prevent the form from being submitted when the enter key is pressed.
+4
A:
if(characterCode == 13)
{
return false; // returning false will prevent the event from bubbling up.
}
else
{
return true;
}
Ok, so imagine you have the following textbox in a form:
<input id="scriptBox" type="text" onkeypress="return runScript(event)" />
In order to run some "user defined" script from this text box when the enter key is pressed, and not have it submit the form, here is some sample code. Please note that this function doesn't do any error checking and most likely will only work in IE. To do this right you need a more robust solution, but you will get the general idea.
function runScript(e) {
if (e.keyCode == 13) {
var tb = document.getElementById("scriptBox");
eval(tb.value);
return false;
}
}
returning the value of the function will alert the event handler not to bubble the event any further, and will prevent the keypress event from being handled further.
Josh
2009-05-25 03:35:11
How do a call another user defined javascript function ?
Shyju
2009-05-25 03:40:40
What exactly do you mean by user defined? Like, the user types some script in a text box and you run it using Eval()???
Josh
2009-05-25 03:43:38
A:
Override the onsubmit action of the form to be a call to your function and add return false after it, ie:
<form onsubmit="javascript:myfunc();return false;">
rpkelly
2009-05-25 03:40:51