[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 409
  • Last Modified:

Return ('Enter') submits form using javascript?

Hi there,

I have a form on a website that uses a button (input="button") and some javascript to trigger a form submit after first using some ajax code.

What can I do if I want the form to be submitted when someone presses the return key? and have it work in most browsers?

Thanks,
Ant
0
antum
Asked:
antum
3 Solutions
 
BraveBrainCommented:
Change the button from
<input type="button"
to
<input type="submit"

Then put the javascript that needs to be called on submit in the form tag in this syntax:
<form onsubmit="doSomething(); doSomethingElse()"

If you've got a function that needs to cancel the submit if it returns false you can do that this way:
<form onsubmit="return doSomething();"

If doSomething then returns false it will cancel the submit. (Same as just saying onsubmit="return false;")
0
 
JaaxCommented:
For the editable elements (Textbox, Textarea, SelectBox etc ) in the form have

onKeyPress="checkEnter(event)"


In your script define this function

function checkEnter(e){
            var characterCode
            if(e && e.which){
                  e = e
                  characterCode = e.which
            }else{
                  e = event
                  characterCode = e.keyCode
            }

            if(characterCode == 13){
                //Change this according to your form
                  document.forms[0].submit()
                  return false
            }else{
                  return true
            }
      }

0
 
ZvonkoSystems architectCommented:

put this in the body tag:
<body onKeyDown="kC=(event.which)?event.which:event.keyCode;if(kC==13)document.forms[0].yourButtonName.click()">


0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
BraveBrainCommented:
There's no need to check for keypress and which key was pressed, as adding a submit button to your form automatically listens for the enter key.
0
 
ZvonkoSystems architectCommented:
My code works also for <select> boxes and even when no form element is focused.
0
 
antumAuthor Commented:
I found all of these solutions helpful... thanks very much!
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now