我有以下ajax和jquery代码,当用户单击表单上的提交按钮时运行该代码。但是,我还想在用户点击回车键时运行代码?有人可以告诉我该怎么做吗?提前致谢
我试过这个但是如果我这样做的话似乎根本不起作用:
$(document).on('keypress click', '#submit', function() {
代码:
<script type="text/javascript">
$(document).ready(function() {
$(document).on('keypress click', '#submit', function() {
var myusername = $("#myusername").val();
var mypassword = $("#mypassword").val();
if (myusername == null || myusername == "" || mypassword == null || mypassword == "") {
if (myusername == null || myusername == "") { document.forms["form"]["myusername"].style.border = "2px solid #963634";}
if (mypassword == null || mypassword == "") { document.forms["form"]["mypassword"].style.border = "2px solid #963634";}
$( ".home_column" ).effect( "shake" );
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("include/validate_login.php", {
username1: myusername,
password1: mypassword
}, function(data) {
if (data.indexOf("login_wrong") >= 0){
$(".home_column").flip({
direction:'lr',
color: 'rgba(138, 138, 138, 0.2)',
content:'<h21>Incorrect Login Details</h21>'
})
setTimeout(
function()
{
$(".home_column").revertFlip()
}, 2500); }else{
if (data.indexOf("login_success") >= 0){
$(".home_column").flip({
direction:'lr',
color: 'rgba(138, 138, 138, 0.2)',
content: '<h21>Hello '+data.substring(13)+'</h21><br/><br/><h21>Please Wait...</h21>'
})
setTimeout(
function()
{
window.location = 'dashboard.php';
}, 2500);
} }
$('#form')[0].reset(); // To reset form fields
});
}
});
});
</script>
答案 0 :(得分:1)
您需要在按键功能中执行此操作,然后您可以检查是否按下了“输入”(13)并提交表单。
function submitForm() {
//Form submission functionality goes here
}
$("input").keypress(function(e) {
if (e.which === 13) {
e.preventDefault();
submitForm();
}
});
$("#formID").submit(function(e) {
e.preventDefault();
submitForm();
});
答案 1 :(得分:0)
只需将要运行的代码放在函数中,然后为click事件和keypress事件(如APAD1解释)调用该函数。
// bind UI actions
$(document).on('click', '#submit', myFunc);
$("input").keypress(function(e) {
if (e.which === 13) {
myFunc();
}
});
// functions
function myFunc() {
// place your code here
}