Genadinik
Genadinik

Reputation: 18629

How to make the Enter button do something else rather than submit a form?

I have a form in which I use autocomplete, and a link. When some text is entered into the form, and the link is clicked, the contents of the text go into the the textarea.

You can see it working in this test page: http://www.problemio.com/test.php

The problem I am having is that when the cursor is in the textfield, and "enter" is pressed, the form gets submitted. But the more intuitive thing is that the "add category" link gets clicked.

Is there a way to change things so that when the cursor is on the textfield, and enter is pressed, the page acts as though the link for "add category" is pressed?

Thanks!!

Upvotes: 1

Views: 556

Answers (3)

ConnorLaCombe
ConnorLaCombe

Reputation: 320

You can add the onsubmit event to your form tag. So it looks like this:

<form onsubmit="return doSubmit();">

Then in your JavaScript you can have:

function doSubmit() {
    //Do all your JS stuff here
    document.getElementById("addCategoryId").click(); //Not sure if this is completely right, but that will click your addCategory button/link as long as the ID is set correctly.

    return false; //Don't submit form
}

Upvotes: 1

Roman Goyenko
Roman Goyenko

Reputation: 7070

You can override the pressing of the Enter in the form:

<script type="text/javascript">

function stopRKey(evt) {
  var evt = (evt) ? evt : ((event) ? event : null);
  var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
  if ((evt.keyCode == 13) && (node.type=="text"))  {return false;}
}

document.onkeypress = stopRKey;

</script> 

Upvotes: 2

Fatih Acet
Fatih Acet

Reputation: 29529

What about to use a normal button instead of submit. You can bind click to it and do what you want even submit a form.

Upvotes: 1

Related Questions