本文介绍了输入密钥以提交Ajax表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个非常简单的AJAX表单,该表单要求提供电子邮件地址,并在提交后将其发送给我.
I have a very simple AJAX form that asks for an email address and sends it to me after submitting.
当我按下Enter键时,如何获得要提交的表格?
How can I can I get the form to submit when hitting the enter key?
这在用户单击提交"按钮时运行:
This runs when user clicks submit button:
<script type="text/javascript">
$(document).ready(function () {
$("#submit_btn").click(function () {
// Get input field values:
var user_email = $('input[name=email]').val();
// Simple validation at client's end
// We simply change border color to red if empty field using .css()
var proceed = true;
if (user_email === "") {
$('input[name=email]').css('border-color', 'red');
proceed = false;
}
// Everything looks good! Proceed...
if (proceed) {
/* Submit form via AJAX using jQuery. */
}
});
// Reset previously set border colors and hide all message on .keyup()
$("#contact_form input, #contact_form textarea").keyup(function () {
$("#contact_form input, #contact_form textarea").css('border-color', '');
$("#result").slideUp();
});
});
</script>
我知道之前曾有人问过这个问题-我无法使keypress
函数正常工作.
I know this question has been asked before -- I'm having trouble getting the keypress
function to work.
我尝试这样做无济于事
$("#contact_form").keypress(function (e) {
if ((e.keyCode == 13) && (e.target.type != "textarea")) {
e.preventDefault();
// Get input field values
var user_email = $('input[name=email]').val();
// Simple validation at client's end
// We simply change border color to red if empty field using .css()
var proceed = true;
if (user_email === "") {
$('input[name=email]').css('border-color', 'red');
proceed = false;
}
// Everything looks good! Proceed...
if (proceed) {
/* Submit form via AJAX using jQuery. */
}
}
});
表格为#contact_form
.
任何帮助将不胜感激...
Any help would be would appreciated…
推荐答案
只需将Submit事件绑定到您的表单,然后回车键也将起作用:
Just bind the submit event to your form, and then the enter key will also work:
$("#contact_form").submit(function (e) {
e.preventDefault();
// Get input field values
var user_email = $('input[name=email]').val();
// Simple validation at client's end
// We simply change border color to red if empty field using .css()
var proceed = true;
if (user_email === "") {
$('input[name=email]').css('border-color', 'red');
proceed = false;
}
if (proceed) {
// Insert the AJAX here.
}
});
代码在这里: http://jsfiddle.net/6TSWk/6/
这篇关于输入密钥以提交Ajax表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!