I have a script that validates a form (using jQuery Validate) and then submits data. It’s currently working great, but now I need to add a checkbox and I’m not clear on how to submit the value using jquery/ajax. Do I need to include something like $('#checkBox').attr('checked');? And if so, how do I pass that on to ajax?
Also, when I click “submit”, without having completed the form, the checkbox auto-checks itself. Why is this happening?
jquery:
<script>
$(document).ready(function(){
$("#formid").validate({
rules: {
name: "required",
email: {
required: true,
email: true
},
mobile: {
required: true,
minlength: 10
},
news: {
required: false,
}
},
messages: {
name: "Please enter your name",
email: "Please enter a valid email address",
mobile: "Please enter your mobile number"
},
submitHandler: function() {
var name = $('#name').attr('value');
var email = $('#email').attr('value');
var mobile = $('#mobile').attr('value');
var news = $('#news').attr('value');
$.ajax({
type: "POST",
url: "ajax.php",
data: $("#formid").serialize(),
success: function(){
$('form#formid').hide();
$('div.success').fadeIn();
}
});
return false;
}
});
});
</script>
form:
<form id="formid" method="post">
<fieldset>
<div>
<label for="name">Name</label>
<input type="text" id="name" name="name" class="required" />
</div>
<div>
<label for="email">Email</label>
<input type="text" id="email" name="email" class="required" />
</div>
<div>
<label for="mobile">Mobile</label>
<input type="text" id="mobile" name="mobile" class="required" />
</div>
<label for="news"><p>Please don’t send me ongoing news</p>
<input type="checkbox" id="news" name="news" value="No" />
<label for="submit1" id="submit"><span> </span>
<input id="submit1" type="submit" name="submit" value="Submit"/>
</label>
</fieldset>
</form>
You have an unclosed
labeltag that the browser is extending to encompass both thecheckboxand thesubmitbutton.This is causing both the
checkboxandsubmitto act as if they were clicked when either of them is clicked.Fixing your markup should solve your issue.