I have a form which I want to submit only if a condition is true. But there is also a case in which I want to programmatically.
Following works when manually submitting the form:
<input type="submit" value="submit" onclick="return checkForTheCondition();"/>
Following works for the submitting the form programmatically but it doesn't check for the condition for submitting the form.
$('form').submit();
So I tried to do the following for programmatically checking the condition before submitting the form but when I use the following code it doesn't even submit the form which was being done by $('form').submit();:
$('form').submit(function() {
return checkForTheCondition();
});
checkForTheCondition() returns either true or false.
Is it possible to programmatically submit the form just like it works for manual form submission where it checks for a condition before submitting the form?
You should be able to do it this way:
if (checkForTheCondition()) {
$('form').submit();
}
Edit: I think I understand your problem now.
Calling $('form').submit(function () { ... }); does NOT trigger the event. The function is not a callback! Instead it binds the function to the submit event. So when you call this:
$('form').submit(function() {
return checkForTheCondition();
});
You do not trigger the event, insted you bind return checkForTheCondition(); this is somewhat the same as onclick="return checkForTheCondition();" but it will be called everytime the form is submitted, and not only when the submit button is clicked.
I would do it this way:
<input type="submit" value="submit">
<script>
$(document).ready(function () {
$('form').submit(function() {
return checkForTheCondition();
});
});
</script>
Then you can just call $('form').submit(); and checkForTheCondition() will be called each time. You can read more about jQuery and submit here.
Good luck
Edit again:
I realise the easiest solution would be this:
<form method="post" action="somepage" onsubmit="return checkForTheCondition();">
<!-- Inputs -->
<input type="submit" value="submit">
</form>
This will make $('form').submit(); and clicks on the submit button call checkForTheCondition() before submitting. Enjoy!
Your code should work if it returns true/false conditionally. You can try this if you want to alert any message on failure of condition.
$(function(){
$('form').submit(function() {
if(!checkForTheCondition()){
//alert message here
return false;//This will stop the form from being submitted.
}
return true;
});
});
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