If you are using type="submit" then if the validation fails, you need to stop the default action by returning false from the validation method. and changing the event handler to
<button type="submit" onclick="return checkMandatoryFieldsAndSubmit()"/> Submit </button>
then
function checkMandatoryFieldsAndSubmit() {
var error = false;
$.map($('.mandatory_field'), function (element) {
//error = false;
if ($(element).attr('type') == "text") {
if ($(element).val() == "") {
error = true;
$(element).parent().addClass('unset');
} else {
$(element).parent().removeClass('unset');
}
}
if ($(element).attr('type') == "checkbox") {
if ($(element).attr('checked') == false) {
error = true;
$(element).parent().addClass('unset');
} else {
$(element).parent().removeClass('unset');
}
}
if ($(element).attr('type') == "radio") {
var radio_error = true;
//check all having the same name!
var name = $(element).attr('name');
$('input[name="' + name + '"]').each(function (index) {
if (radio_error) {
if ($(this).attr('checked') == false) {
radio_error = true;
} else {
radio_error = false;
}
}
});
if (radio_error) {
error = true;
$(element).parent().addClass('unset');
} else {
$(element).parent().removeClass('unset');
}
}
});
if (!error) {
$('#form').submit();
} else {
$('#error').show();
}
//return the valid state here
return !error;
}
Demo: Fiddle
Also I would recommend using onsubmit
event instead of onclick
event
<form action="http://www.aol.com" method="post" id="myform" onsubmit="return checkMandatoryFieldsAndSubmit()">
<input name="carname" type="text" value="" class="mandatory_field" />
<button type="submit">Submit</button>
</form>
Demo: Fiddle