我有一个表单,我需要在提交之前填写所有字段。目前,正在验证字段以检查它们是否为空。但是,如果按下“提交”按钮而未在字段中输入任何值,则表单将发送所有返回空白的字段(例如姓名:电话:等)。我已经尝试在表单字段中添加HTML5“required”属性,但这并不能解决非HTML5兼容浏览器或IE的问题。
我想知道你是否可以帮助我解决这个问题......谢谢!
在我的页面顶部,我放了:
<script>
$(function(){
$('#message_form').validate({
submitHandler: function(form) {
$(form).ajaxSubmit({
url: 'process.php',
success: function() {
$('#message_form').hide();
$('#contact_form').append("<p id='message_form_thanks'>Thanks! Your request has been sent.</p>")
}
});
}
});
});
</script>
process.php代码为:
<?php
// Get Data
$name = strip_tags($_POST['name']);
$phone = strip_tags($_POST['phone']);
$email = strip_tags($_POST['email']);
$message = strip_tags($_POST['message']);
// $url = strip_tags($_POST['url']);
// Send Message
mail( "mailto:postmaster@domain.com", "Contact Form Submission",
"Name: $name\nPhone: $phone\nEmail: $email\nMessage: $message\n",
"From: Website Form Enquiry <$email>" );
?>
我的表单代码为:
<form id="message_form" method="post">
<div class="success">Contact form submitted! <strong><br>We will be in touch soon.</strong></div>
<fieldset>
<label class="name"><span class="formlabel"> Name:</span>
<input type="text" name="name" placeholder="Please provide your full name" required>
<span class="error">*This is not a valid name.</span>
<span class="empty">*This field is required.</span>
<span class="clear"></span>
</label>
<label class="phone"><span class="formlabel">Phone:</span>
<input type="text" name="phone" placeholder="Example: (555) 555-5555" required>
<span class="error">*This is not a valid phone number.</span>
<span class="empty">*This field is required.</span>
<span class="clear"></span>
</label>
<label class="email"><span class="formlabel">Email:</span>
<input type="text" name="email" placeholder="Please provide your email address" required>
<span class="error">*This is not a valid email address.</span>
<span class="empty">*This field is required.</span>
<span class="clear"></span>
</label>
<span class="formlabel_message">Message:</span>
<label class="message">
<textarea name="message" placeholder="Please enter your message here" style="margin-top:0;" required></textarea>
<span class="error">*The message is too short.</span>
<span class="empty">*This field is required.</span>
<span class="clear"></span>
</label>
<div class="buttons-wrapper"><a class="button-2 mobile_noshow" data-type="reset">reset</a>
<input type="submit" name="submit" class="button-2" style="margin:0 0 0 7px;border:none;" id="submit" value="Send" /></div>
</fieldset>
</form>
答案 0 :(得分:3)
你需要做一些验证,我可能会禁用提交按钮,直到所有字段都填满,如下所示:
$('#message_form #submit').attr('disabled', 'disabled');
$('#message_form input,textarea').on('keyup', function(){
if($('#name').val() && $('#phone').val() && $('#email').val() && $('#message').val()){
$('#message_form #submit').removeAttr("disabled");
}
else{
$('#message_form #submit').attr('disabled', 'disabled');
}
});
这是fiddle