我有一个表格。我想要提交表单的唯一方法是使用提交按钮。我想确保不使用ios上的Enter按钮或go按钮提交表单。

最佳答案

HTML

<input type="button">不会使用Enter键或移动设备上的“执行”按钮触发自动提交。

<form action="my-handler.php" method="POST" id="my_form">

    <label for="some_input">Input 1
    <input name="some_input" id="some_input" type="text">
    </label>

    <label for="another_input">Input 2
    <input name="another_input" id="another_input" type="text">
    </label>

    <input type="button" value="Submit Form" id="submit_button">

</form>


JavaScript

<script type="text/javascript">

    // Stop the form from submitting if enter is pressed
    // or the 'go' button is pressed on mobile
    $( '#my_form' ).submit(function(e) {

        e.preventDefault();

    });

    // Submit the form when button is clicked
    $( document ).on( 'click', '#submit_button', function() {

        $( '#my_form' ).submit();

    });

</script>


结论

您可能不应该过多地关注防止在移动设备上使用Enter或“ go”提交表单,因为这会降低用户体验。我想您正在这样做,因为在填写表单之前,有些事情很容易触发提交。也许,在这种情况下,表单验证对您来说是一个更好的朋友,例如:

<script type="text/javascript">

    $( '#my_form' ).submit( function(e) {

        e.preventDefault(); // Don't let the form submit yet

        if( true == validateForm() ) {
            $( '#my_form' ).submit(); // Submit the form
        } else {
            // Show error output
        }

    });

    // Validation function - returns true or false
    function validateForm() {
        // Do all your field validation and return
        return true;
    }

</script>

关于javascript - 表单只能使用“提交”按钮提交,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34501620/

10-12 00:21
查看更多