I've got a form with a textbox. When I press Enter in the textbox, I don't want the form to submit; instead I want to call a JS function. How would I do that?
Printable View
I've got a form with a textbox. When I press Enter in the textbox, I don't want the form to submit; instead I want to call a JS function. How would I do that?
for IE anyway:
:)Code:fucntion Text1_KeyPress()
{
if (event.keyCode == 13)
{
event.returnValue = false;
//call JS function here.
}
}
<form>
<input type="text" onKeyPress="Text1_KeyPress()"/>
</form>
Does it work in NS or have you just not tested it?
Untested. I don't think I've ever tested for cross-browser compatability, I just hope for the best.Quote:
Originally posted by filburt1
Does it work in NS or have you just not tested it?
:)
Well it works great in IE but surprise surprise, NS managed to screw it up. But there's nothing in the JS Console ("javascript:" in the location bar), it just does nothing making me assume "onKeyPress" isn't supported:
Code:<script language="javascript">
<!--
function transferKeyEvent()
{
if (event.keyCode == 13)
{
event.returnValue = true;
submitSearch();
}
}
// -->
</script>
<input width="100%" type="text" onKeyPress="transferKeyEvent()" name="q">
Well, from what I understand, NS has a totally different event handling scheme than IE, so, it wouldn't be that its not supported, just called in a different way. I haven't coded for NS in a long while, so it could have changed since then.
On second look, you are setting event.returnValue to True, try setting it to False.Quote:
Originally posted by filburt1
Well it works great in IE but surprise surprise, NS managed to screw it up. But there's nothing in the JS Console ("javascript:" in the location bar), it just does nothing making me assume "onKeyPress" isn't supported:
Code:<script language="javascript">
<!--
function transferKeyEvent()
{
if (event.keyCode == 13)
{
event.returnValue = true;
submitSearch();
}
}
// -->
</script>
<input width="100%" type="text" onKeyPress="transferKeyEvent()" name="q">
:)
Good point but no change. :(Quote:
Originally posted by crptcblade
On second look, you are setting event.returnValue to True, try setting it to False.
:)
This thread is going in the wrong direction.
Here is the answer to the question
This is cross browser compatiable and works a treat.Code:<script>
function checkMyForm(the_form){
//do some errror checking
//if everything is ok
if(the_form.mytext.value == "hello world"){
the_form.submit();
//else if we need more input
}else{
alert("please enter the correct phrase !");
}
return false;
}
</script>
<form name="myform" method="post" action="some.cgi" onSubmit="return checkMyForm(this)">
<input type="text" name="mytext">
</form>
If you need me to explain how this method works and what it is doing just ask !! :cool: