我正在尝试实时检查数据库中的输入字段。我在下面有 java 脚本:
$(document).ready(function(){
$('#emailcheck').load('check-email.php').show();
$(".next").click(function() {
$.post('check-email.php', { email: form.email.value },
function(result) {
$('#emailcheck').html(result).show();
});
});
});
HTML:
<form name="email">
<input type="email" class="form-control" id="email" name="email" placeholder="email"><br>
<div id="emailcheck"></div>
</form>
<p><a class="btn btn-primary next">Go to step 2</a></p>
如您所见,当我单击 .next
时,它会在 #emailcheck
中告诉我电子邮件是否可用。
如果我从 check-email.php
获取的结果是“可用”,那很好。
但是结果是“Taken”,例如,我怎么能阻止 .next
发生呢?因为我希望用户在下一步之前修复该字段。
我也将其他 Java 脚本代码用于相同的表单:
// jQuery.validate script, does client-side validation
$(document).ready(function(){
$(".next").click(function(){
var form = $("#myform");
form.validate({
errorElement: 'div',
errorClass: 'formerror',
highlight: function(element, errorClass, validClass) {
$(element).closest('.form-group').addClass("has-error");
},
unhighlight: function(element, errorClass, validClass) {
$(element).closest('.form-group').removeClass("has-error");
},
rules: {
username: {
required: true,
minlength: 1,
remote: {
url: "check-username.php",
async: false,
type: "post", }
},
email: {
required: true,
minlength: 1,
remote: {
url: "check-email.php",
async: false,
type: "post", }
},
},
messages: {
username: {
required: "Username required",
remote: "taken",
},
email: {
required: "Email required",
},
}
});
if (form.valid() === true){
if ($('#stepusername').is(":visible")){
current_fs = $('#stepusername');
next_fs = $('#stepemail');
}else if($('#stepemail').is(":visible")){
current_fs = $('#stepemail');
next_fs = $('#stepsuccess');
}
next_fs.show();
current_fs.hide();
}
});
});
// prevent sending empty and stuff
$(document).ready(function(){
$('.form-horizontal').keypress(function (event) {
if (event.which === 13) {
event.preventDefault();
$(".next").trigger('click');
}
});
});
// For server-side validation.
$(document).ready(function(){
$(function(){
$('input[type=submit]').click(function(){
if($("#myform").valid()){
$.ajax({
type: "POST",
url: "sent.php",
data: $("#myform").serialize(),
beforeSend: function(){
$('#stepsuccess').html('Loading...');
},
success: function(data){
$('#stepsuccess').html(data);
}
});
}
});
});
});
最佳答案
您实际要做的是阻止“下一个”点击事件的默认行为。因此,您应该将事件声明为 $(".next").click(function(event){
然后在 if (form.valid())
之后的底部> 你应该添加:
if (form.valid() === true){
// everything you originally had here
} else {
event.preventDefault();
}
关于javascript - 在 jQuery 的帮助下防止用户进入 ".next",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32317938/