I have the following spring form that execute back end controller and JavaScript function, everything work but I need to execute JavaScript function before submitting the form. How to do that?
The following code submit the form before execute JavaScript.
<form:form modelAttribute="api" id="form">
<form:textarea path="text" class="form-control" rows="10" id="redacttext"/>
<button type="submit" class="btn btn-default">Submit</button>
</form:form>
Javascript function
function dosomething() {
//do something
}
Execute javascript function by jquery
$('#form').submit(function() {
dosomething();
});
here is the working example.
$('#submit').on('click',function() {
dosomething();
});
function dosomething() {
console.log('here');
//return false;
// if you want to submit the form here
$('#form').submit();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form:form modelAttribute="api" id="form">
<form:textarea path="text" class="form-control" rows="10" id="redacttext" />
<button type="button" id="submit" class="btn btn-default">Submit</button>
</form:form>
You can try this
$("#form").submit(function(e) {
e.preventDefault();
..... do you action/ call custom function
this.submit();
return false; //I put it here as a fallback
});
Try to use the preventDefault Event
$('#form').submit(function(e) {
e.preventDefault();
dosomething();
});
and in your dosomething() function at the end add:
$( "#form" ).submit();
This will first run your dosomething() function and then thru the function, it will submit your form.
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