Getting HTML form values

JavascriptHtml

Javascript Problem Overview


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>

Javascript Solutions


Solution 1 - Javascript

HTML:

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

JS:

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

Solution 2 - Javascript

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

JavaScript

const formData = new FormData(document.querySelector('form'))
for (var pair of formData.entries()) {
  // console.log(pair[0] + ': ' + pair[1]);
}

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

serialize(document.forms[0]);

jQuery

$("form").serializeArray()

Solution 3 - Javascript

I found this the most elegant solution.

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

Solution 4 - Javascript

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.

Solution 5 - Javascript

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);

Solution 6 - Javascript

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

Solution 7 - Javascript

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;

Solution 8 - Javascript

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.

Solution 9 - Javascript

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

Solution 10 - Javascript

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>

Solution 11 - Javascript

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.

Solution 12 - Javascript

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>

Solution 13 - Javascript

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>

Solution 14 - Javascript

<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"}
    */
}

Solution 15 - Javascript

<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>

Solution 16 - Javascript

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"] }

Solution 17 - Javascript

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)
}

Solution 18 - Javascript

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')

Solution 19 - Javascript

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser377419View Question on Stackoverflow
Solution 1 - Javascriptuser406632View Answer on Stackoverflow
Solution 2 - JavascriptKevin FarrugiaView Answer on Stackoverflow
Solution 3 - JavascriptDedaDevView Answer on Stackoverflow
Solution 4 - JavascriptTran Nguyen Nhat ThuyView Answer on Stackoverflow
Solution 5 - JavascriptCodeaculaView Answer on Stackoverflow
Solution 6 - JavascriptjhaavistView Answer on Stackoverflow
Solution 7 - JavascriptKlesunView Answer on Stackoverflow
Solution 8 - JavascriptRusca8View Answer on Stackoverflow
Solution 9 - JavascriptAtav32View Answer on Stackoverflow
Solution 10 - JavascriptМаксим ЩирыйView Answer on Stackoverflow
Solution 11 - JavascriptUlviView Answer on Stackoverflow
Solution 12 - JavascriptBlakeWebbView Answer on Stackoverflow
Solution 13 - JavascriptB''H Bi'ezras -- Boruch HashemView Answer on Stackoverflow
Solution 14 - JavascriptДаниил ПронинView Answer on Stackoverflow
Solution 15 - JavascriptVijay Shankar TiwariView Answer on Stackoverflow
Solution 16 - JavascriptJon CatmullView Answer on Stackoverflow
Solution 17 - JavascriptDeepak kumar debugView Answer on Stackoverflow
Solution 18 - JavascriptsmartexpertView Answer on Stackoverflow
Solution 19 - JavascriptRandhawaView Answer on Stackoverflow