Advertisement:
Read Later
In this tutorial, I will show you how to send form data to a specific page without including a submit button automatically in plain JavaScript. In other words, after taking this tutorial, you will be able to create polls, user interfaces, surveys, etc., without either adding a submit button or forcing the user to take action.
As an example, I programmed a rudimentary form to elucidate coding steps. But, you can improve the design in your projects merely with CSS.
HTML:
- Create a form element and input variables - text, number, and radio.
- Define each input element by unique name attributes - firstname, lastname, age, and news.
JavaScript:
- By using the addEventListener() method, detect whether the user inserts new information to the form.
- Get values from the input variables in the form.
- Use the :checked pseudo-class to get information from the checked radio buttons with the same name attribute.
- If all required variables are given, print all variables to let the user check recently transferred values.
- Otherwise, print "Waiting..."
- Then, initiate the setTimeout() function for 500 milliseconds to stop reading new values and send current information entered by the user via an AJAX (asynchronous HTTP) request.
-------------- HTML --------------
<form>
<fieldset>
<legend>Test</legend>
<label>First Name: </label><input type="text" name="firstname" placeholder="Testing..."></input><br><br>
<label>Last Name: </label><input type="text" name="lastname" placeholder="Testing..."></input><br><br>
<label>Age: </label><input type="number" name="age" min="1" max="120" value="18"></input><br><br>
<label>Subscribe to Newsletter: </label><input name="news" type="radio" value="yes"></input> <input name="news" type="radio" value="no"></input><br><br>
<p style="text-align:center;">Waiting...</p>
</fieldset>
</form>
-------------- JavaScript --------------
document.querySelector("form").addEventListener("input", () => {
clearTimeout();
var first_name = document.querySelector('input[name="firstname"]').value;
var last_name = document.querySelector('input[name="lastname"]').value;
var age = document.querySelector('input[name="age"]').value;
var news = document.querySelector('input[name="news"]:checked').value;
if(first_name && last_name && age && news){
document.querySelector("form p").innerHTML = "Success!!!<br>First Name: " + first_name + "<br>Last Name: " + last_name + "<br>Age: " + age + "<br>Newsletter: " + news;
setTimeout(function(){
$.ajax({
url: "?firstname=" + first_name + "&lastname=" + last_name + "&age=" + age + "&newsletter=" + news,
type: "GET"
});
}, 500);
}else{
document.querySelector("form p").innerHTML = "Waiting...";
}
});
Result: