I am trying to execute some code in order, but cannot get it to work. What I want to do is:
var validate = function($form) {
$form
.find('[data-required]')
.each(function() {
if(Util.isEmpty($(this).val())) {
$(this).addClass('error');
Util.Notify(Util.ERROR, $(this).data('required'));
return false;
}
else {
$(this).removeClass('error');
}
});
};
var submit = function($form) {
$.post(actionUrl, $form.serialize(), function(response) {
//...
});
};
validate(); // must execute first with no False return
submit(); // must execute second and only if validate() not returns False
However, my $.post() gets executed even if validate() returns false. How can I force submit() to be executed after validate is executed and did not return false? I googled and tried a few example based on what people posted, but was unsuccessful.
validatedoesn't return anything. Also you're not passing it any parameters even though it expects one. You need to havevalidatereturn something then you can doif(validate()){ submit(); }.each's callback and notvalidate.if(validate()) { submit(); }. To make this work,validateshould returntrue(validated) orfalse(not validated).