Adam Tomat
Adam Tomat

Reputation: 11516

Stop form submitting when clicking 'Go' on mobiles

Is there a way to link a button to an input, so mobiles know what to do when you press Next or Go on the keyboard within a .NET context (i.e. Pressing 'Go' on an input fakes the click on the next button instead of submitting the form)?

Let's talk code for a second. I have the following markup, where injected-via-js is injected via javascript into a large form (progressive enhancement).

<form class="dotNET-form-wrapper">
    <div class="injected-via-js">
        <div>
            <span>&pound;</span>
            <input type="number" />
        </div>
        <div>
            <button>accept</button>
        </div>
    </div>

    <!-- More form elements -->
</form>

On most mobile browsers, when you change the value in the number input and press Go or Enter it fakes the button press (which in my case has an important event bound to it). However on some old Android devices pressing Go will submit the form instead, which is not what I want. To clarify: I want the Go button to fake the button press, not submit the form.

Note: .NET is only relevant to this question due to the fact that everything is wrapped in a form, meaning I cannot create a separate form around the input and button and highjack the new form's submit.

I've made a JSBin where I was able to replicate this bug with an Android 2.2 phone although I imagine it exists on other bad browsers as well. It works as expected on iOS 6+ and Android 2.3+.

Here's the demo page: http://jsbin.com/tebizoda/2

And here's the edit version: http://jsbin.com/tebizoda/2/edit

Upvotes: 3

Views: 2936

Answers (1)

Natalia
Natalia

Reputation: 308

Both "Go" and "Enter" has keycodes like the enter on the keyboard (13) so you should just make a JavaScript or jQuery function that overrides the default behaviour and just triggers the button press. Something like (example in jQuery):

$(your_form_or_input).keypress(function (e) {
  if (e.keyCode == 13) {
    return false;
  } else {
    // your code here...
  }
});

Mind that some browsers use e.keyCode, others e.which to determine the pressed key code.

Upvotes: 4

Related Questions