Asked 7 years ago
19 Dec 2016
Views 1140
fatso

fatso posted

how to submit form automatically by javascript

for some reason i want to auto submit form by JavaScript

following is HTML FORM for add to cart page.

<form action="addtocart.php" name="add to cart">
<input type="hidden" name="product_id"  />
</form>


how to auto submit FORM without any action like clicking button or without other trigger or action by user ?
Form should be auto submit without any action .
open for JavaScript or jQuery code.
lain

lain
answered Apr 24 '23 00:00

To submit a form automatically using JavaScript, you can use the submit () method of the HTMLFormElement object. Here's how you can do it:

1.Get a reference to the form element: You can use the . gedocumenttElementById () or document.querySelector() method to get a reference to the form element. For example, if you have a form with an id attribute of myForm , you can get a reference to it like this:



const form = document.getElementById('myForm');

2.Call the submit () method: Once you have a reference to the form element, you can call the submit() method to submit the form. For example, you can use the following code to submit the form automatically when the page loads:



window.onload = function() {
  const form = document.getElementById('myForm');
  form.submit();
};

This code uses the onload event handler to submit the form automatically when the page finishes loading.

Alternatively, you can use an event listener to submit the form automatically when a specific event occurs, such as when a button is clicked. For example, you can use the following code to submit the form automatically when a button with an id attribute of myButton is clicked:



const button = document.getElementById('myButton');
button.addEventListener('click', function() {
  const form = document.getElementById('myForm');
  form.submit();
});

This code adds an event listener to the button element that listens for the click event. When the button is clicked, the code gets a reference to the form element and calls the submit () method to submit the form.

By following these steps, you can submit a form automatically using JavaScript.
Post Answer