- Setting the Form Action with a JavaScript Function
- 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
- Calling Form Action in JavaScript: A Guide
- Call js function from form action then call php from js
- Form action Attribute in JavaScript
- Another Example Using Form action JavaScript
- Alternative Way to Use Form Action Attribute in JavaScript
- JavaScript Form
- Can the form action attribute call a javascript function in an external javascript file?
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:
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.
Calling Form Action in JavaScript: A Guide
In HTML, the form attribute example allows for the submission of input data to a given link for processing. In JavaScript, the attribute specifies the designated location for the form data to be sent upon submission.
Call js function from form action then call php from js
Assigning an ID to your FORM is the initial step to enable the possibility of accomplishing the task.
then in javascript try this:
var myForm = document.getElementById('myForm'); myForm.addEventListener('submit', function(e) < var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() < if (xhttp.readyState == 4 && xhttp.status == 200) < document.getElementById("result").innerHTML = xhttp.responseText; >>; xhttp.open("POST", filename.php, true); xhttp.send(); e.preventDefault(); >);
Form action Attribute in JavaScript
The submission destination for form data is specified by the action attribute.
Another Example Using Form action JavaScript
This instance showcases the utilization of a form attribute in an HTML code snippet as illustrated below: action
In the above code, we have incorporated a personalized form action utilizing JavaScript.
Alternative Way to Use Form Action Attribute in JavaScript
When a user submits the form, the desired outcome can be obtained through the onsubmit event.
The onsubmit function is utilized for submitting form data, rather than relying on the form action attribute.
JavaScript Form
Get action of submitted form, $(«form»).submit(function() < //do some generic stuff var formAction = "";
Can the form action attribute call a javascript function in an external javascript file?
To call a function within a script file, simply include the file using the code , and the program will automatically locate the function. This is made possible through the use of , which allows all script code to be contained within the file.
onsubmit="SubmitFormViaAjax();return false;"
By preventing the form from submitting itself (using «return false»), you can utilize any function within the form to directly submit its data to the recipient through ajax.
Ensure that the ajax functions file is incorporated into the page.
Calling Javascript from a html form, You can either use javascript url form with