Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute Javascript function before submitting the form

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();
  });
like image 542
Ali-Alrabi Avatar asked Nov 23 '17 15:11

Ali-Alrabi


3 Answers

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>
like image 84
Abid Nawaz Avatar answered Oct 17 '22 19:10

Abid Nawaz


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
});
like image 26
thiyagu selvaraj Avatar answered Oct 17 '22 21:10

thiyagu selvaraj


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.

like image 25
zagzter Avatar answered Oct 17 '22 20:10

zagzter