views:

14052

answers:

2

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
How do a call another user defined javascript function ?
Shyju
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
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
I cant override onsubmit as i have another form submit in this page
Shyju
yes you can.Javascript is prototype based language.document.forms["form_name"].onsubmit = fucntion() {}
the_drow
I have another delete procedure to run when the form is submitted.So i want to maintain as it is
Shyju

related questions