Home > front end >  How do I extract form data in html with js
How do I extract form data in html with js

Time:02-10

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

<form action="" method="get" >
    <div >
      <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" >
              ↑

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

CodePudding user response:

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  onsubmit="foo()">
    <div >
      <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>

  •  Tags:  
  • Related