Reputation: 26565
I need a way to submit the form ONLY if foo return true. I tried this code but it submits the form even if foo return false.
<input type="submit" value="submit" onclick="return foo();" />
<script type="text/javascript">
function foo() {
// if... return true
// else return false
}
</script>
If I use the onsubmit function, then it submits first. So it's not good in my case.
Upvotes: 3
Views: 8025
Reputation: 49774
One possible solution is to use the form's submit event. You can put the conditional in the submit event handler so the submission is halted when foo()
does not return true.
(NOTE: I had to guess what the selector might be for your form since it's not part of your question)
document.getElementById('myForm').submit(function(e) {
if (!foo()) {
e.preventDefault();
}
})
Upvotes: 1
Reputation: 3427
you can try alternative method using jquery ajax submit as follows, which I am using, may helpful to u too..
var request;
$("#YourFormId").submit(function(event){
if(yourFunction()==false) {
return false;
}
if (request) {
request.abort();
}
var $form = $(this);
var $inputs = $form.find("input, select, button, textarea");
var serializedData = $form.serialize();
$inputs.prop("disabled", true);
request = $.ajax({
url: "yourFormActionPage.php",
type: "post",
data: serializedData
});
request.done(function (response, textStatus, jqXHR){
//ok
});
request.fail(function (jqXHR, textStatus, errorThrown){
//track it
});
request.always(function () {
$inputs.prop("disabled", false);
});
event.preventDefault();
});
Upvotes: 2
Reputation: 587
You can use ajax submit.
<form class="formbox" method="post" action="/your/action/url" id="myForm" name="myForm">
<input type="text" id="name" class="name" name="name" value=""/>
<input type="submit" value="submit" onclick="return foo();" />
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function foo() {
if(1==1) {
alert("Success: Going to call the function");
$("#myForm").submit(); //calling function.
} else {
alert("Error: ");
}
}
Upvotes: 0