请你看一下这个link,让我知道为什么我不能在用<form> ... </form>
标签包裹时验证表格?
正如您从代码中看到的那样,我可以在<fieldset> </fieldset>
内部声明时验证它,我试图将id="contact_form"
移动到表单标记中:
<form id="contact_form">
但它也不起作用!正如我所说,我可以在没有<form>
的情况下完成这个过程,但是我必须将我的样式从Bootstrap 3框架添加为:
<form class="form-inline" role="form" id="contact_form">
这是我的整个HTML代码:
<form class="form-inline" role="form" id="contact_form">
<fieldset id="contact_form">
<legend>My Contact Form</legend>
<div id="result"></div>
<label for="name"><span>Name</span>
<input type="text" name="name" id="name" placeholder="Enter Your Name" />
</label>
<label for="email"><span>Email Address</span>
<input type="text" name="email" id="email" placeholder="Enter Your Email" />
</label>
<label for="phone"><span>Phone</span>
<input type="text" name="phone" id="phone" placeholder="Phone Number" />
</label>
<label for="message"><span>Message</span>
<textarea name="message" id="message" placeholder="Enter Your Name"></textarea>
</label>
<label><span> </span>
<button class="submit_btn" id="submit_btn">Submit</button>
</label>
</fieldset>
</form>
答案 0 :(得分:1)
您必须阻止表单标记内的提交按钮的默认行为。我想这就是你要找的东西:
$("#submit_btn").click(function(e) {
e.preventDefault();
//get input field values
var user_name = $('input[name="name"]').val();
var user_email = $('input[name="email"]').val();
var user_phone = $('input[name="phone"]').val();
var user_message = $('#contact_form textarea').val();
//simple validation at client's end
//we simply change border color to red if empty field using .css()
var proceed = true;
if(user_name==""){
$('input[name="name"]').css('border-color','red');
proceed = false;
}
if(user_email==""){
$('input[name="email"]').css('border-color','red');
proceed = false;
}
if(user_phone=="") {
$('input[name="phone"]').css('border-color','red');
proceed = false;
}
if(user_message=="") {
$('#contact_form textarea').css('border-color','red');
proceed = false;
}