在基于jQuery的表单上禁用Enter键 [英] Disable the enter key on a jquery-powered form

查看:328
本文介绍了在基于jQuery的表单上禁用Enter键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用jQuery表单插件处理数据发布的表单.在示例中,我正在处理的数据被存储到另一个php文件中,该文件读取数据库并回显显示在from下方的结果.

I have a form using the form jQuery plug in to handel the posting of the data. In the example i am working with the data is psoted to another php file which reades a database and echos back a result which is displayed below the from.

该代码在出现小故障时效果很好.如果在选择文本字段时单击回车按钮,则将清除所有内容,包括已写入屏幕的结果.是否可以禁用输入密钥并阻止其执行此操作?

The code works very well with one glitch. If you hit the enter button while the text filed is selected everything cleared including the result that has been written to the screen. Is it possible to disable to enter key and prevent it from doing this?

FORM:

<html>
<head>
</head>
<p>enter code here
<form name="form" action="" method="">
  <label for="name" id="name_label">Name</label> 
  <input type="text" name="name" id="name"/>
  <input type="button" value="get" onclick="get();"/>
</form>

<div id="age"></div>
</p>
</body>
</html>

脚本:

function get() {
    $.post('data.php', {name: form.name.value},
        function(output) {
            $('#age').hide().html(output).fadeIn(1000);
        });
    }
}

干杯.

推荐答案

您应该考虑使用 jQuery Forms插件.这将使您免于进行一些繁琐的工作,此外,它将拦截所有提交表单的方式-因此,不必禁用RETURN键,它将通过AJAX提交您的表单.

You should consider using the jQuery Forms Plugin. It will save you from doing some of the dirty work, additionally it will intercept all ways of submitting the form - so instead of having to disable the RETURN key it will submit your form via AJAX.

如果您不希望这样做,请使用onclick事件删除按钮,然后将其替换为提交"按钮,然后将功能注册为onsubmithandöer:

If you don't want that, get rid of the button with the onclick event and replace it with a submit button and register your function as a onsubmit handöer:

$('form[name=form]').submit(function(e) {
    e.preventDefault();
    $.post('data.php', {name: form.name.value},
        function(output) {
            $('#age').hide().html(output).fadeIn(1000);
        });
    }
});

这篇关于在基于jQuery的表单上禁用Enter键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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