How do I run a function from an external file as an action for a form?

Description:

I currently have a html file with a form similar to the following:

<form id="my_form" action="javascript:OnAction()" method='post' >
</form>

      

I have a javascript function "OnAction ()" in an external file like script.js.

Problem:

The OnAction () function does not run if it is in an external file (in html this function is run). Other scripts in the external file are executed (this means the script file is linked correctly).

Question:

How can I trigger the OnAction () function on my form action and hold it in an external file?

Is there a way to link something like:

$('#my_form').on('action', function() {
    // OnAction here
});

      

+3


source to share


4 answers


Change your HTML to:

<form id="my_form" action="" onSubmit="OnAction()" method='post'></form>

      

You just need to do this:

function OnAction() {
    // OnAction here
};

      

Or a better way to host your event with JQuery:



HTML:

<form id="my_form" action="" method='post'></form>

      

JS:

$("#my_form").on("submit", function() {
    /* OnAction here*/
});

      

+2


source


$('#my_form').on('action', function() {

      



The event that fires when the form is submitted, submit

not action

. Use this (with real url in action with server side fallback in case of JS failure, don't forget preventDefault()

).

+1


source


Add a link to your external file to your HTML file.

0


source


In your HTML:

...
<form method="post" id="myform">
<input type="submit"/>
</form>

<script src="abc.js" type="text/javascript">

</script>
</body>

      

In your js. File:

var elem = document.getElementById("myform");
elem.addEventListener("submit", function() {
   //
},false);

      

-1


source







All Articles