What I want to do is following: At first, function validate()
must check all inputs one by one: if they are not empty (or whitespaced) then move to if statement (for checking radio buttons) But if some of inputs empty then stop whole validate function and focus on empty input.
Here is result: http://jsfiddle.net/tt13/y53tv/4/
Just press ok
button, you'll see that it finished first function and fires if too. But I want to exit from whole validate() function in case there is empty field, not only from each() function
JS
function validate() { $('.var_txt').each(function() { if ($.trim($(this).val()) == '') { $(this).focus(); return false; } }); if (!$(".answer:checked").val()) { alert("boom"); return false; } return true; } $(document).ready(function() { $("#add_question").submit(function(e) { if (validate()) { alert("good"); } e.preventDefault(); }) });
HTML Markup
<form id="add_question" method="post" action=""> <table> <tr> <td class="var_label"> <input class="answer" type="radio" name="answer" value="a" /> a) </td> <td> <input type="text" class="var_txt" name="var_a" /> </td> </tr> <tr> <td class="var_label"> <input class="answer" type="radio" name="answer" value="b" /> b) </td> <td> <input type="text" class="var_txt" name="var_b" /> </td> </tr> <tr> <td class="var_label"> <input class="answer" type="radio" name="answer" value="c" /> c) </td> <td> <input type="text" class="var_txt" name="var_c" /> </td> </tr> <tr> <td class="var_label"> <input class="answer" type="radio" name="answer" value="d" /> d) </td> <td> <input type="text" class="var_txt" name="var_d" /> </td> </tr> <tr> <td class="var_label"> <input class="answer" type="radio" name="answer" value="e" /> e) </td> <td> <input type="text" class="var_txt" name="var_e" /> </td> </tr> </table> <input type="submit" name="submit" value="ok" /> </form>
A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call.
Break is mostly used to exit from loops but can also be used to exit from functions by using labels within the function.
Sometimes when you're in the middle of a function, you want a quick way to exit. You can do it using the return keyword. Whenever JavaScript sees the return keyword, it immediately exits the function and any variable (or value) you pass after return will be returned back as a result.
Add a flag that has to be false to continue.
function validate() { var invalid = false; $('.var_txt').each(function() { if ($.trim($(this).val()) == '') { $(this).focus(); invalid = true; return false; } }); if (invalid) { return false; } if (!$(".answer:checked").val()) { alert("boom"); return false; } return true; } $(document).ready(function() { $("#add_question").submit(function(e) { if (validate()) { alert("good"); } e.preventDefault(); }) });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With