jQuery,禁止输入表单提交但允许通过单击按钮提交表单 [英] jQuery, prevent form submit from enter but allow form submit by button click

查看:141
本文介绍了jQuery,禁止输入表单提交但允许通过单击按钮提交表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单,其中在输入文本框中输入数字,然后按Enter,然后使用jQuery将值附加到文本区域.一切正常.

I have a form where in an input text box I enter a number and press ENTER and I use jQuery to append the value to a textarea. This all works fine.

我遇到的问题是,如果我添加了一个提交按钮来提交表单,那么当我按下ENTER键时,它就会提交表单.

The problem I'm having is that if i add a submit button to submit the form, as soon as i press ENTER, it submits the form.

我要执行的操作不是在按Enter键时提交表单,而是仅在单击提交"按钮时提交表单.

What I want it to do is not submit the form on pressing enter but submit the form ONLY when the submit button is clicked.

我尝试使用preventDefault()并返回false,这将在按ENTER时停止提交表单,但是如果我在提交按钮上添加click事件以提交表单,则不会执行任何操作.我在提交之前的点击功能中添加了一个警告,该警告会触发但表单未提交

I've tried using preventDefault() and return false which will stop the form submitting on pressing ENTER but if i add a click event on the submit button to submit the form, it does nothing. I've put an alert in the click function before the submit and that fires but form doesn't submit

<form id="toteform" method="post" action="blah.php">
    <input type="text" name="bin" id="bin" maxlength="4" autocomplete="off" />

    <input type="text" name="totes" id="tote" maxlength="4" autocomplete="off" />

    <input type="button" name="submit" class="submit" id="submit" value="Submit" />
</form>

jQuery

$("#submit").click(function() {
    $('#toteform').submit();
});

$('#bin').focus();

$('#bin').keypress(function(e) {
    if(e.which == 13) {
        $('#tote').focus();
    }
});

$('#tote').keypress(function(e) {
    if(e.which == 13) {

    // more code here to do other things

推荐答案

我找到了解决方法

$("#toteform").submit(function(e) {
    if (e.originalEvent.explicitOriginalTarget.id == "submit") {
        // let the form submit
        return true;
    }
    else {
        //Prevent the submit event and remain on the screen
        e.preventDefault();
        return false;
    }
});

这篇关于jQuery,禁止输入表单提交但允许通过单击按钮提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆