Categories
JavaScript Answers

How to change value of input and submit form in JavaScript?

Spread the love

Sometimes, we want to change value of input and submit form in JavaScript.

In this article, we’ll look at how to change value of input and submit form in JavaScript.

How to change value of input and submit form in JavaScript?

To change value of input and submit form in JavaScript, we can set the value property of the input.

For instance, we write

<form id="myForm" action="action.php">
  <input type="hidden" name="myInput" value="0" id="myInput" />
  <input type="text" name="message" value="" />
  <input type="submit" name="submit" />
</form>

to add a form.

Then we write

const myForm = document.getElementById("myForm");

myform.onsubmit = () => {
  document.getElementById("myInput").value = "1";
  myForm.submit();
};

to call getElementById to get the form.

Then we set its onsubmit property to a function that’s called when we submit the form.

In it, we get the input with getElementById and set its value to '1'.

And then we call submit to submit the form.

Conclusion

To change value of input and submit form in JavaScript, we can set the value property of the input.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.