- How to call javascript function from form action attribute
- Step1: Create the HTML Form
- JavaScript Function
- Attaching the Function to the Form
- Full Demo
- How to create the server-side script that receives the form submissions
- Pro Tip: Attach a form handler with just one line of code
- See Also
- Calling Javascript from a html form
- 6 Answers 6
- How can I set the form action through JavaScript?
- 8 Answers 8
How to call javascript function from form action attribute
HTML forms are an essential element of web pages that enable users to enter and send data. Upon clicking the submit button, the information is transmitted to the server via an HTTP request. The form’s action attribute specifies the URL where the data should be delivered.
While creating web applications, it’s common to have forms that enable users to enter and submit data. However, sometimes you may need to perform some actions on the client-side before submitting the form data to the server. This is where JavaScript comes in handy, allowing you to add interactivity to the form.
In this tutorial, we’ll show you how to use JavaScript to handle form submissions by calling a function when the form is submitted.
Step1: Create the HTML Form
First, let’s start with the HTML form. We will create a simple form that contains an input field for the user’s name and a submit button.
h2>Feedbackh2> div class="p-4"> form id="myform"> div class="form-group"> label for="myform_name">Namelabel> input type="text" name="name" class="form-control" id="myform_name" placeholder="Your Name"> div> div class="form-group"> label for="myform_email">Email address:label> input type="email" name="email" class="form-control" id="myform_email" placeholder="Your email"> div> div class="form-group"> label for="myform_message">Messagelabel> textarea class="form-control" name="message" id="myform_message" rows="3">textarea> div> button type="submit" class="btn btn-primary">Submitbutton> form> div>
Note that we have added an id attribute to the form element. This will allow us to reference the form in our JavaScript code later.
JavaScript Function
Next, we need to create a JavaScript function that will be called when the form is submitted. The function will take an event object as its parameter, which will allow us to prevent the default form submission behavior.
function handleSubmit(event) event.preventDefault(); var myform = document.getElementById("myform"); var formData = new FormData(myform); fetch("https://show.ratufa.io/json", method: "POST", body: formData, >) .then(response => if (!response.ok) throw new Error('network returns error'); > return response.json(); >) .then((resp) => let respdiv = document.createElement("pre"); respdiv.innerHTML = JSON.stringify(resp, null, 2); myform.replaceWith(respdiv); console.log("resp from server ", resp); >) .catch((error) => // Handle error console.log("error ", error); >); >
The function starts by calling event.preventDefault() to prevent the form from being submitted in the default way, which would cause a page refresh.
Then, the function gets a reference to the form element with the id of «myform» using document.getElementById(«myform») and assigns it to the variable myform .
Next, it creates a new FormData object, passing in the myform element as an argument. This object contains the form data that will be sent to the server.
The fetch function is then called to make a network request to the URL “https://show.ratufa.io/json» using the HTTP method “POST”. The FormData object is passed as the request body using the body option.
If the network request is successful and the response from the server has a 200 status code, the response body is returned as JSON using the response.json() method. If the response has a different status code, an error is thrown.
If the response is successfully parsed as JSON, the function creates a new pre element using document.createElement(«pre») . It then sets the innerHTML of the pre element to the response JSON stringified with two spaces for indentation using JSON.stringify(resp, null, 2) . The myform element is then replaced with the pre element using myform.replaceWith(respdiv) . Finally, the response is logged to the console using console.log(«resp from server «, resp) .
If there is an error during the network request or parsing of the response JSON, the error is caught and logged to the console using console.log(«error «, error) .
Attaching the Function to the Form
Now that we have our HTML form and JavaScript function, we need to attach the function to the form so that it is called when the form is submitted.
We can do this by using the addEventListener() method to add an event listener to the form. We will listen for the submit event, which will be triggered when the user clicks the submit button.
var myform = document.getElementById("myform"); myform.addEventListener("submit", submitForm);
Full Demo
How to create the server-side script that receives the form submissions
Even though you have completed your form with a button to submit the form, you still need a server-side script that will receive the form submission and perhaps sends you an email and saves the form data to a database for record keeping.
The easier solution is to use a service like Ratufa.io. With Ratufa.io, you don’t need any PHP script or worry about configuring PHP email or SMTP. All you need to do is copy just one line of code to your HTML page and get full backend support for your form instantly.
Pro Tip: Attach a form handler with just one line of code
Ratufa is a form back-end as service. You just have to add one line of code to your form page and the form immediately becomes fully functional.
See Also
Calling Javascript from a html form
I am basing my question and example on Jason’s answer in this question I am trying to avoid using an eventListener , and just to call handleClick onsubmit , when the submit button is clicked. Absolutely nothing happens with the code I have. Why is handleClick not being called?
edit: Please do not suggest a framework as a solution. Here are the relevant changes I have made to the code, which results in the same behavior.
function handleClick() < alert("Favorite weird creature: "+getRadioButtonValue(document.myform['whichThing']))); event.preventDefault(); // disable normal form submit behavior return false; // prevent further bubbling of event >
none of the methods would work in modern browsers if you don’t have the attribute sandbox=»allow-scripts» for form element. w3schools.com/Tags/att_iframe_sandbox.asp
@MuhammadUmer — AFAIK, the sandbox attributes are only needed when you explicitly create an iframe that is a sandbox. If your HTML iframe does not contain the attribute «sandbox», or you don’t have an iframe, then how could these restrictions be in effect?
FWIW, the moral of this Q&A is «when it doesn’t work, remove stuff from your code, until you find what does work, then work back towards your error». If the alert was simplified to alert(«Favorite weird creature»); , OP would have discovered that worked (the alert appears), and then would have known he had some problem in the syntax of . getRadioButtonValue(..) . Successive iterations from what worked towards what doesn’t work could have isolated the problem to this[«whichThing»] isn’t returning a value. A much simpler Q&A to have: replace that with document.aye.whichThing . Solved.
6 Answers 6
You can either use javascript url form with
Or use onSubmit event handler
In the later form, if you return false from the handleClick it will prevent the normal submision procedure. Return true if you want the browser to follow normal submision procedure.
Your onSubmit event handler in the button also fails because of the Javascript: part
EDIT: I just tried this code and it works:
Joshxtothe4 is right. his alert is failing, not primarily because his function isn’t being called, nor because it’s being called twice due to doubling the javascript event call, but because the this[«whichThing»] construct is causing an error.
Note that using onSubmit is the correct approach for forms. Also between onSubmit & action , onSubmit will be triggered first.
getRadioButtonValue(this["whichThing"]))
you’re not actually getting a reference to anything. Therefore, your radiobutton in the getradiobuttonvalue function is undefined and throwing an error.
EDIT To get the value out of the radio buttons, grab the JQuery library, and then use this:
$('input[name=whichThing]:checked').val()
Edit 2 Due to the desire to reinvent the wheel, here’s non-Jquery code:
or, basically, modify the original line of code to read thusly:
getRadioButtonValue(document.myform.whichThing))
Edit 3 Here’s your homework:
function handleClick() < alert("Favorite weird creature: " + getRadioButtonValue(document.aye.whichThing)); //event.preventDefault(); // disable normal form submit behavior return false; // prevent further bubbling of event >
Notice the following, I’ve moved the function call to the Form’s «onSubmit» event. An alternative would be to change your SUBMIT button to a standard button, and put it in the OnClick event for the button. I also removed the unneeded «JavaScript» in front of the function name, and added an explicit RETURN on the value coming out of the function.
In the function itself, I modified the how the form was being accessed. The structure is: document.[THE FORM NAME].[THE CONTROL NAME] to get at things. Since you renamed your from aye, you had to change the document.myform. to document.aye. Additionally, the document.aye[«whichThing»] is just wrong in this context, as it needed to be document.aye.whichThing.
The final bit, was I commented out the event.preventDefault();. that line was not needed for this sample.
EDIT 4 Just to be clear. document.aye[«whichThing»] will provide you direct access to the selected value, but document.aye.whichThing gets you access to the collection of radio buttons which you then need to check. Since you’re using the «getRadioButtonValue(object)» function to iterate through the collection, you need to use document.aye.whichThing.
See the difference in this method:
How can I set the form action through JavaScript?
I have an HTML form whose action should be set dynamically through JavaScript. How do I do it? Here is what I am trying to achieve:
8 Answers 8
You cannot invoke JavaScript functions in standard HTML attributes other than onXXX . Just assign it during window onload.
window.onload = function() < document.myform.action = get_action(); >function get_action()
You see that I’ve given the form a name , so that it’s easily accessible in document .
Alternatively, you can also do it during submit event:
Although, depending on markup this may not validate, the ‘name’ attribute is not a valid attribute in XML, its better to use an ID and use the getElementById
@Rabbott: It’s HTML, not XML. XHTML is only interesting for server-side HTML-autogenerators like componentbased MVC frameworks.
document.getElementById('form_id').action; //Will retrieve it document.getElementById('form_id').action = "script.php"; //Will set it
$("#form_id").attr("action"); //Will retrieve it $("#form_id").attr("action", "/script.php"); //Will set it
Hi, I think for plain JavaScript line 2: document.getElementById(‘form_id’).action = «script.php» will retrieve it
It was a nice option, I used the Plain Javascript Option. I worked in the desktop view. But not getting that worked with mobile browsers
Very easy solution with jQuery:
$('#myFormId').attr('action', 'myNewActionTarget.html');
Actually, when we want this, we want to change the action depending on which submit button we press.
Here you do not need even assign name or id to the form. Just use the form property of the clicked element:
Change the action URL of a form:
. assuming it is the first form on the page.
this might work, but i am still trying to make it work by getting the action string from a function. is there no way to do it like that?
You can write it in an onsubmit event handler to make sure it always gets just just before submission. However, in general trying to change a form action from script is a code smell; unless you don’t control the server side, it’s usually better to make the form accept two+ different submission modes.