Milktea
Milktea

Reputation: 161

Formless "form" submission using enter button

We are currently building an application using Dojo Mobile and there are several areas where we have input fields and submit buttons. These input fields and submit buttons do are not in a form, and we just use onclick events to "submit" the values in the fields to be utilized in the javascript. Is there a way to make it so that when we press "enter", or, in the case of mobile applications, when the user presses "search" or "go" on their soft keyboard, it will trigger that particular button? We could potentially have multiple submit buttons on the same page.

 ...
<div>
    <input dojoType="dijit.form.TextBox" />
    <button dojoType="dijit.form.Button" type="submit">
        Filter
    </button>
<div>
 ...

Upvotes: 0

Views: 1068

Answers (3)

ChaseMoskal
ChaseMoskal

Reputation: 7681

Overriding the Default Form Submit Action

You can override the default submit action on a form. It's semantically wise to keep your forms within <form> tags, even when you want to override the default behavior, and do what you want, as the strong, independent black woman that you are.

jsFiddle

HTML:

<form id="myForm">
    <input type="text" />
    <button type="submit">Submit</button>
</form>

JavaScript:

var myForm = document.getElementById('myForm');
myForm.addEventListener('submit',function(event){
    alert('submit pressed -- do as you please');
    event.preventDefault(); // cancels form submission
});

//Chase.

Upvotes: 1

Steve H.
Steve H.

Reputation: 6947

Place your related fields in a form. Register an "onsubmit" event handler and make it the same as your "onclick" handler for the button. When you return from the event handler, you should either return false or you should call event.preventDefault(). This will prevent the form from being submitted (via POST) to the server.

Upvotes: 1

kirkas
kirkas

Reputation: 1859

solution in JQuery:

//when you a key on an input
$("input").keyup(function (e) {
    //if it is enter
    if (e.keyCode == 13) {
        //look for the next submit button a trigger a click
        $(this).next("button[type='submit']").click();
    }
});

I'm not a dojo-coder but the documentation seems quite good:

http://dojotoolkit.org/documentation/tutorials/1.6/key_events/

http://dojotoolkit.org/api/1.6/dojo/keys/ENTER

see here for related answer:

Enter key press event in JavaScript

http://dojo-toolkit.33424.n3.nabble.com/want-enter-key-in-ValidationTextBox-to-submit-the-form-td977303.html

Upvotes: 1

Related Questions