简体   繁体   中英

Android and HTML5 Number Input AutoSubmit Behavior

I am writing an web page that has a form with a single zipcode field for estimating shipping and taxes. I would like the form to submit once the user hits the enter key on the numeric keypad.

eg

<form method="GET">
    <input type="hidden" id="ProductCode" value="12345" />
    Enter zip: <input type="number" id="ZipCode" />
</form>

The current behavior is apparently not obvious enough:

<script>
$(document).ready(function() {
    $('#ZipCode').keyup(function() {
        if($(this).val().length == 5) {
            $(this).closest('form').submit();
        }
    });
    $('#ZipCode').focus(function() {
        $(this).val('');
    });
});
</script>

Ideally I would like the form to autosubmit when the enter key is closed or (if possible) when the soft keyboard is closed by the user. Is there any way to do this using JavaScript in the Android browser?

You could try to add hidden button. This works at least in Chrome. When form has a submit button it is automatically triggered when enter is pressed.

<form method="GET">
    <input type="hidden" id="ProductCode" value="12345" />
    Enter zip: <input type="number" id="ZipCode" />
    <button type="submit" style="display:none">
</form>

The you can use $("form").submit(function(){ // run when form is submitted }) to implement the submit code.

Put a submit button in the form and the enter key will submit the form naturally.

<form method="GET">
    <input type="hidden" id="ProductCode" value="12345" />
    Enter zip: <input type="number" id="ZipCode" />
    <input type="submit" value="submit" style="visibility: hidden" /> 
</form>

If you need to validate bind to the form submit event, and perform your necessary validation there.

$('form').submit(function() {
    var invalid = $('#ZipCode').val().length !== 5;
    if(invalid)
        return false
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM