My form has some fields that are mandatory and I have marked them with class="required". I am writing the below jquery to validate this form, but it doesn’t happen. I think either I am messing with calling the two functions or I am not getting the proper element through $(this).
<script type="text/javascript">
function validatemyForm() {
$('.required').each(function() {
if($(this).val() == "" || $(this).replace(/\s/g, '').length == 0)
{
$(this).insertAfter('<span>This is a Required Filed</span>');
return false;
}
else {
$(this).remove();
}
})
return true;
}
</script>
I am calling the form, from the onsubmit event handler <form id="myform" onsubmit ="return validatemyForm();">. Am I incorrectly using each and this of jQuery?
A number of things:
You can use
replaceon a String, whilst you use it on a jQuery object. There is no$(this).replace. If you want to check for whitespace, you need the value, i.e.$(this).val().replace.You use
$(this).insertAfterwhich means that the input element is inserted after the span.$(this).removesimply removes the input element which isn’t what you’re after either I think.You
return falsein theeach(), but this doesn’t return that value in thevalidatemyFormfunction. In that function, you alwaysreturn true.I changed it to this to get it working: http://jsfiddle.net/DaDQT/6/.