- 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
- Setting the Form Action with a JavaScript Function
- Form action Property
- Browser Support
- Syntax
- Property Values
- Technical Details
- More Examples
- Example
- Related Pages
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Form Action Attribute in JavaScript
- Form action Attribute in JavaScript
- action Attribute Values
- Form action Attribute Example Using HTML
- Another Example Using Form action JavaScript
- Alternative Way to Use Form Action Attribute in JavaScript
- Related Article — JavaScript Form
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.
Setting the Form Action with a JavaScript Function
In an HTML form, the action attribute is used to indicate where the form’s data is sent to when it is submitted. The value of this can be set when the form is created, but at times you might want to set it dynamically. In this tutorial, we’ll look at ways in which a form’s action attribute can be set dynamically by JavaScript.
To get started, create an HTML file and paste the following form to its body.
form onsubmit="return setAction(this)"> div> label>Name:label> input id="name" name="name" type="text"> div> div> label>Email:label> input id="email" name="email" type="email"> div> div> input id="submit" type="submit"> div> form>
The above markup is for a simple form with two fields and a submit button. We’ve set an onsubmit listener which will be called when the form is submitted. This will, in turn, make a call to the setAction() function that we’ll soon define. In the function call, the form passes a reference to itself ( this ).
Add the following CSS styling:
form label display: inline-block; width: 100px; > form div margin-bottom: 10px; >
Add the following JavaScript to the file.
function setAction(form) form.action = "register.html"; alert(form.action); return false; >
In the above, we assign the passed in form reference to the form variable. Then we set its action attribute with form.action = «register.html» . This will result in the form’s action getting set to BASE_URL/register.html . The BASE_URL will be the URL the HTML file is running on. To test that the action was set, we display its value in an alert box. The function then returns false to prevent the form from getting submitted. This is included in the demo code since the /register.html page doesn’t exist, but in a real application, you would want the form to be submitted.
Next, we’ll look at another example where the form action will be set depending on the button used to submit the form.
You can add the following to the HTML file.
form name="user_form"> div> label>Email:label> input id="user_email" name="user_email" type="email"> div> div> label>Password:label> input id="user_password" name="user_password" type="password"> div> div> input id="login" type="submit" value="Login" onclick="return loginUser()"> div> div> input id="register" type="submit" value="Register" onclick="return registerUser()"> div> form>
The above form has two buttons that have been set up with onclick listeners. Each listener makes a call to a different button when clicked.
Add the following JavaScript to the file.
function loginUser() document.user_form.action = "login.html"; alert(document.user_form.action); return false; > function registerUser() document.user_form.action = "register.html"; alert(document.user_form.action); return false; >
loginUser() gets called when the Login button is clicked. The function sets /login.html as the value of the form’s action attribute. In this example, we get a reference to the form with document.user_form . For this to work, the name attribute of the form has to be set to user_form . After setting the action attribute, we alert the value and return false thus preventing form submission.
registerUser is called when the Register button is clicked and it sets ./register.html as the form’s action.
See the code in action below:
Form action Property
The action property sets or returns the value of the action attribute in a form. The action attribute specifies where to send the form data when a form is submitted.
Browser Support
Syntax
Property Values
Value | Description |
---|---|
URL | Specifies where to send the form data when the form is submitted. |
- An absolute URL — points to another web site (like action=»http://www.example.com/example.htm»)
- A relative URL — points to a file within a web site (like action=»example.htm»)
Technical Details
More Examples
Example
Return the URL for where to send the form data when a form is submitted:
Related Pages
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Form Action Attribute in JavaScript
- Form action Attribute in JavaScript
- Another Example Using Form action JavaScript
- Alternative Way to Use Form Action Attribute in JavaScript
This article explains JavaScript’s form action attribute. It accesses the form, gets values of all fields, validates form data, and sends it to the right destination. Let’s look at what these action attributes are and how they work.
We can create a form in this way.
form action="/signup" method="post" id="signup"> form>
Form action Attribute in JavaScript
The action attribute specifies where to send the form data when submitted.
action Attribute Values
- Absolute URL — it points to another website (like action=»https://www.delftstack.com/tutorial/javascript» )
- Relative URL — it points to a file within a website (like action=»example.htm» )
Form action Attribute Example Using HTML
Send the form data to a given link to process the input on submitting.
form action="https://www.delftstack.com" method="get"> label for="firstname">First name:label> input type="text" id="firstname" name="firstname">br>br> label for="lastname">Last name:label> input type="text" id="lastname" name="lastname">br>br> input type="submit" value="Submit"> form>
Another Example Using Form action JavaScript
The following example includes an HTML from using a form action attribute.
html lang="en"> head> title>Form action javascripttitle> style> form label display: inline-block; width: 100px; > form div margin-bottom: 10px; > style> head> body> div class="p-2"> form id="myForm"> div> label>Name:label> input id="name" name="name" type="text"> div> div> label>Email:label> input id="email" name="email" type="email"> div> div> input id="submit" type="submit"> div> form> div> body> script> // setting action on window onload event window.onload = function () setAction('action.php'); >; // this event is used to get form action as an alert which is set by setAction function by using getAction function document.getElementById('submit').addEventListener('click', function (e) e.preventDefault(); getAction(); >); // this function is used to set form action function setAction(action) document.getElementById('myForm').action = action; return false; > // this function is used to get form action assigned by setAction function in an alert function getAction() var action = document.getElementById('myForm').action ; alert(action); > script>
We have added custom form action using JavaScript in the code above.
Alternative Way to Use Form Action Attribute in JavaScript
The same results are achievable using the onsubmit event when a user submits the form.
form onsubmit="myFunction()"> div> label>Name:label> input id="name" name="name" type="text"> div> div> label>Email:label> input id="email" name="email" type="email"> div> div> input id="submit" type="submit"> div> form>
In the example above, the onsubmit event is used to submit form data instead of the form action attribute.
Related Article — JavaScript Form
Copyright © 2023. All right reserved