rram
rram

Reputation: 2024

How to trigger two function on form submit?

I have a form when the form is submitted i'll call one javascript function and action it to to form handler.

<form action="subscribe.php" onsubmit="return form_check(this)" method="post">
<input type="text" value="">
<input type="submit" value="click">
</form>

Everything Works fine, Now i want to send the same form fields to another javascript function so i tried like this on submit code

    <form action="subscribe.php" 
onsubmit="return (form_check(this) & another_script(this))" method="post">

Added & in onsubmit but the function is not triggering when the button is clicked. I think this is due to the action="subscribe.php" in the form.

I want to send the form value to another javascript function also. how can i achieve this?

Upvotes: 0

Views: 3023

Answers (4)

Moob
Moob

Reputation: 16184

onsubmit="return ((form_check(this) + another_script(this))===2);"

Demo fiddle

Upvotes: 0

Mike Christensen
Mike Christensen

Reputation: 91600

There's a few answers depending on what you're trying to do.

If you want to simply run both functions and not return anything, you can simply do:

onsubmit="form_check(this); another_script(this);"

If you want to always run another_script but return the value of form_check, you can do:

onsubmit="another_script(this); return form_check(this);"

If you want to only run another_script if form_check returns true (and return true if both form_check and another_script return true), you can do:

onsubmit="return form_check(this) && another_script(this);"

However, putting too much code in an onsubmit handler is usually discouraged. You should bind event handlers after using the DOM or jQuery.

Upvotes: 1

andi
andi

Reputation: 6522

Does this work?

onsubmit="another_script(this); return form_check(this);"

of course, it's always better to use unobtrusive event handlers.

Upvotes: 0

kunalbhat
kunalbhat

Reputation: 1719

With jQuery you can catch the form submit. The submit event is sent to an element when the user is attempting to submit a form.

HTML

<form id="myForm">...</form>

jQuery

$("#myForm").submit(function(event){
  event.preventDefault();

  var this = something;

  myFunctionA(this);
  myFunctionB(this);
});

var myFunctionA = function(this){
  // Function operation
}

var myFunctionB = function(this){
  // Function operation
}

Upvotes: 1

Related Questions