0

I'm trying to create a web app, and I need to know the user input from form.

<form action="" method="get" class="settings">
    <div class="settings">
      <label for="length">length of character(s): </label>
      <input type="number" name="length" id="length" placeholder="5" required>
      <input type="submit" value="Change">
    </div>
  </form>

I need the form to run a js func foo() so I assume that I need to put it

<form action="" method="get" class="settings">
              ↑

how do I get the value of id="length" and use it in form action"foo()"?

  • I think this post might answer your question https://stackoverflow.com/questions/588263/how-can-i-get-all-a-forms-values-that-would-be-submitted-without-submitting – dasfacc Feb 10 '22 at 03:02

1 Answers1

3

You can get the value of length with document.getElementById("id").value;

In order to run a js from form, you need to use onsubmit="" instead of action=""

onsubmit="" allows you to execute a js function upon submission of the form, while action="" allows you to be redirected to another page/site upon submission.

Read more about action="" in this site

onsubmit="" is here

Here is a workable code based on your example

function foo(){
  var lgt = document.getElementById("length").value;
  alert(lgt);
}
<form class="settings" onsubmit="foo()">
    <div class="settings">
      <label for="length">length of character(s): </label>
      <input type="number" name="length" id="length" placeholder="5" required>
      <input type="submit" value="Change">
    </div>
  </form>
Lucas Lim
  • 123
  • 13
  • this works, but I cant get the data to a function without it having to refresh and loose the variable again. –  Feb 10 '22 at 15:52
  • 1
    you can add a preventdefault() method to the js function foo() { event.preventDefault(); var lgt = document.getElementById("length").value; alert(lgt); } – Lucas Lim Feb 11 '22 at 02:10
  • 1
    alternatively, you can add "return false" into the onsubmit field onsubmit="foo();return false" – Lucas Lim Feb 11 '22 at 02:18