user377419
user377419

Reputation: 4989

Getting HTML form values

How can I get the value of an HTML form to pass to JavaScript?

Is this correct? My script takes two arguments one from textbox, one from the dropdown box.

<body>
<form name="valform" action="" method="POST">

Credit Card Validation: <input type="text" id="cctextboxid" name="cctextbox"><br/>
Card Type: <select name="cardtype" id="cardtypeid">
  <option value="visa">Visa</option>
  <option value="mastercard">MasterCard</option>
  <option value="discover">Discover</option>
  <option value="amex">Amex</option>
  <option value="diners">Diners Club</option>
</select><br/>
<input type="button" name="submit" value="Verify Credit Card" onclick="isValidCreditCard(document.getElementById('cctextboxid').value,document.getElementById('cardtypeid').value)" />
</body>

Upvotes: 241

Views: 979715

Answers (20)

Brandon Gibson
Brandon Gibson

Reputation: 1

You need to add "submit" instead of "click as the type of event in your submit handler fn. This event handler fn will be on the "form" element, so make sure you add an "id" prop it and give it a name. Then add an "id" prop to your input where the type is "text and give that a name too. Finally, use that id to find your input's value with the "value" prop. Look at my code below as an example. Hope it helps.

document.querySelector('#form').addEventListner('submit, (e) => {
 e.preventDefault();
 const usersInput = document.querySelector('#inputVal).value;
 console.log(userInput)
 }
)

Upvotes: -1

Kevin Farrugia
Kevin Farrugia

Reputation: 7439

If you want to retrieve the form values (such as those that would be sent using an HTTP POST) you can use FormData class:

JavaScript

document.getElementById("myForm").addEventListener("submit", function (e) {
  e.preventDefault();

  var formData = new FormData(form);
  // output as an object
  console.log(Object.fromEntries(formData));

  // ...or iterate through the name-value pairs
  for (var pair of formData.entries()) {
    console.log(pair[0] + ": " + pair[1]);
  }
});

Example: https://codepen.io/kevinfarrugia/pen/Wommgd?editors=1111


Alternatively you could use the below less recommended options:

form-serialize (https://code.google.com/archive/p/form-serialize/)

serialize(document.forms[0]);

jQuery

$("form").serializeArray()

Upvotes: 179

DedaDev
DedaDev

Reputation: 5249

I think this is the most elegant solution

function handleSubmit(e) {
  e.preventDefault();
  const formData = new FormData(e.target);
  const formProps = Object.fromEntries(formData);
}

Upvotes: 157

smartexpert
smartexpert

Reputation: 3035

A one liner for ES6

getFormData = (selector) => Object.fromEntries(new FormData(document.querySelector(selector)))

console.log('Output of getFormData:')
console.log(getFormData('#myTargetForm'))
<!DOCTYPE html>
<html>
<body>

<h2>Get Form Data as Javascript Object</h2>

<form id="myTargetForm">
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" value="John"><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname" value="Doe"><br><br>
  <input type="submit" value="Submit">
</form> 
</body>
</html>

Define this function in your Javascript:

getFormData = (selector) => Object.fromEntries(new FormData(document.querySelector(selector)))

Then just call with any selector e.g.: getFormData('#myTargetForm')

Upvotes: 10

debug
debug

Reputation: 373

It's easy with one for-of loop you can get all field values even checkboxes values also.

In your HTML you should bind a handlSubmit() on your forms onsubmit event

<form name="contact_form" 
      id="contact-form" 
      class="form-controller" 
      onsubmit="handleSubmit(event)"
>

in your javascript your code should apply the following logic no matter what name your assigned to your fields.

const handleSubmit = (event)=> {
    event.preventDefault();

    const formData = new FormData(event.target);
    formObj = {};
    
    for (const [fieldName] of formData) {
        const fieldValue = formData.getAll(fieldName);
        formObj[fieldName] = fieldValue.length == 1 ? fieldValue.toString() : fieldValue
    }
    console.log('formObj',formObj)
}

Upvotes: 2

Jon Catmull
Jon Catmull

Reputation: 12752

Some answers above didn't cater for forms with multiple fields with the same name e.g.multiple <input name="categories[]"> so I made this quickly. It expects field with the same name that you want to collect as an array to end in [] as a convention but could be updated to handle other scenarios.

function getFormValues(form) {
  const formData = new FormData(form);
  return Array.from(formData.entries()).reduce((prev, [inputName, val]) => {
    return {
      ...prev,
      [inputName]: inputName.endsWith('[]')
        ? prev[inputName]
          ? [...prev[inputName], val]
          : [val]
        : val,
    };
  }, {});
}

// alternative if you don't like reducers and nested ternary statements
function getFormValues(form) {
  const formData = new FormData(form);
  const values = {};
  for (const [inputName, val] of formData.entries()) {
    if (inputName.endsWith('[]')) {
      values[inputName] = values[inputName] ? [...values[inputName], val] : [val];
    } else {
      values[inputName] = val;
    }
  }
  return values;
}

// then attach this to form submit 
function onSubmit(e) {
   e.preventDefault();
   const values = getFormValues(e.target);
   // etc...
}
     

values gives something like { "single": "something", "categories[]": ["one", "two"] }

Upvotes: 3

Vijay Shankar Tiwari
Vijay Shankar Tiwari

Reputation: 21

<script>
var inputs = document.getElementById("form_id_here").elements;
    for (i = 0; i < inputs.length; i++) {
      if (inputs[i].type === "text" || inputs[i].type === "textarea") {
        console.log(inputs[i].value); // Get value of input tag which you have entered.
      }
    }
</script>

Upvotes: 0

Please try to change the code as below:

<form
   onSubmit={e => {
     e.preventDefault();
     e.stopPropagation();

     const elements = Array.from(e.currentTarget);

     const state = elements.reduce((acc, el) => {
       if (el.name) {
         acc[el.name] = el.value;
       }

       return acc;
     }, {});

     console.log(state); // {test: '123'}
   }}
>
   <input name='test' value='123' />
</form>

Upvotes: 4

<form id='form'>
    <input type='text' name='title'>
    <input type='text' name='text'>
    <input type='email' name='email'>
</form>
const element = document.getElementByID('#form')
const data = new FormData(element)
const form = Array.from(data.entries())
/*
form = [
    ["title", "a"]
    ["text", "b"]
    ["email", "c"]
]
*/
for (const [name, value] of form) {
    console.log({ name, value })
    /*
    {name: "title", value: "a"}
    {name: "text", value: "b"}
    {name: "email", value: "c"}
    */
}

Upvotes: 3

BlakeWebb
BlakeWebb

Reputation: 533

I know this is an old post but maybe someone down the line can use this.

// use document.form["form-name"] to reference the form
const ccForm = document.forms["ccform"];

// bind the onsubmit property to a function to do some logic
ccForm.onsubmit = function(e) {

  // access the desired input through the var we setup
  let ccSelection = ccForm.ccselect.value;
  console.log(ccSelection);

  e.preventDefault();
}
<form name="ccform">
  <select name="ccselect">
    <option value="card1">Card 1</option>
    <option value="card2">Card 2</option>
    <option value="card3">Card 3</option>
  </select>
  <button type="submit">Enter</button>
</form>

Upvotes: 4

Ulvi
Ulvi

Reputation: 1021

This is the answer of your question.

You can pass the values of the form fields to the function by using this.<<name of the field>>.value.

And also changed input submit to button submit. Called the function from form.

<body>
   <form name="valform" method="POST" onsubmit="isValidCreditCard(this.cctextbox.value, this.cardtype.value)">
   Credit Card Validation: <input type="text" id="cctextboxid" name="cctextbox"><br/>
   Card Type: 
   <select name="cardtype" id="cardtypeid">
      ...
   </select>
   <br/>
   <button type="submit">Verify Credit Card</button>
</body>

Technically you can do it in your function by using document.getElementById("cctextboxid"). But his solution is concise and simple code.

Upvotes: 3

jhaavist
jhaavist

Reputation: 711

This is a developed example of https://stackoverflow.com/a/41262933/2464828

Consider

<form method="POST" enctype="multipart/form-data" onsubmit="return check(event)">
    <input name="formula">
</form>

Let us assume we want to retrieve the input of name formula. This can be done by passing the event in the onsubmit field. We can then use FormData to retrieve the values of this exact form by referencing the SubmitEvent object.

const check = (e) => {
    const form = new FormData(e.target);
    const formula = form.get("formula");
    console.log(formula);
    return false
};

The JavaScript code above will then print the value of the input to the console.

If you want to iterate the values, i.e., get all the values, then see https://developer.mozilla.org/en-US/docs/Web/API/FormData#Methods

Upvotes: 27

Quick solution to serialize a form without any libraries

function serializeIt(form) {
  return (
    Array.apply(0, form.elements).map(x => 
      (
        (obj => 
          (
            x.type == "radio" ||
            x.type == "checkbox"
          ) ?
            x.checked ? 
              obj
            : 
              null
          :
            obj
        )(
          {
            [x.name]:x.value
          }
        )
      )
    ).filter(x => x)
  );
}

function whenSubmitted(e) {
  e.preventDefault()
  console.log(
    JSON.stringify(
      serializeIt(document.forms[0]),
      4, 4, 4
    )
  )
}
<form onsubmit="whenSubmitted(event)">
<input type=text name=hiThere value=nothing>
<input type=radio name=okRadioHere value=nothin>
<input type=radio name=okRadioHere1 value=nothinElse>
<input type=radio name=okRadioHere2 value=nothinStill>

<input type=checkbox name=justAcheckBox value=checkin>
<input type=checkbox name=justAcheckBox1 value=checkin1>
<input type=checkbox name=justAcheckBox2 value=checkin2>

<select name=selectingSomething>
<option value="hiThere">Hi</option>
<option value="hiThere1">Hi1</option>
<option value="hiThere2">Hi2</option>
<option value="hiThere3">Hi3</option>
</select>
<input type=submit value="click me!" name=subd>
</form>

Upvotes: 1

Rusca8
Rusca8

Reputation: 602

Expanding on Atrur Klesun's idea... you can just access it by its name if you use getElementById to reach the form. In one line:

document.getElementById('form_id').elements['select_name'].value;

I used it like so for radio buttons and worked fine. I guess it's the same here.

Upvotes: 5

Klesun
Klesun

Reputation: 13673

My 5 cents here, using form.elements which allows you to query each field by it's name, not only by iteration:

const form = document.querySelector('form[name="valform"]');
const ccValidation = form.elements['cctextbox'].value;
const ccType = form.elements['cardtype'].value;

Upvotes: 17

Tran Nguyen Nhat Thuy
Tran Nguyen Nhat Thuy

Reputation: 613

Here is an example from W3Schools:

function myFunction() {
    var elements = document.getElementById("myForm").elements;
    var obj ={};
    for(var i = 0 ; i < elements.length ; i++){
        var item = elements.item(i);
        obj[item.name] = item.value;
    }

    document.getElementById("demo").innerHTML = JSON.stringify(obj);
}

The demo can be found here.

Upvotes: 48

Codeacula
Codeacula

Reputation: 2368

document.forms will contain an array of forms on your page. You can loop through these forms to find the specific form you desire.

var form = false;
var length = document.forms.length;
for(var i = 0; i < length; i++) {
    if(form.id == "wanted_id") {
        form = document.forms[i];
    }
}

Each form has an elements array which you can then loop through to find the data that you want. You should also be able to access them by name

var wanted_value = form.someFieldName.value;
jsFunction(wanted_value);

Upvotes: 32

Atav32
Atav32

Reputation: 1812

Several easy-to-use form serializers with good documentation.

In order of Github stars,

  1. jquery.serializeJSON

  2. jquery-serialize-object

  3. form2js

  4. form-serialize

Upvotes: 2

Randhawa
Randhawa

Reputation: 226

<input type="text" id="note_text" />

let value = document.getElementById("note_text").value;

Upvotes: -1

user406632
user406632

Reputation: 1793

HTML:

<input type="text" name="name" id="uniqueID" value="value" />

JS:

var nameValue = document.getElementById("uniqueID").value;

Upvotes: 163

Related Questions