[javascript] JavaScript - 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>

This question is related to javascript html

The answer is


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.


Quick solution to serialize a form without any libraries

_x000D_
_x000D_
function serializeIt(form) {_x000D_
  return (_x000D_
    Array.apply(0, form.elements).map(x => _x000D_
      (_x000D_
        (obj => _x000D_
          (_x000D_
            x.type == "radio" ||_x000D_
            x.type == "checkbox"_x000D_
          ) ?_x000D_
            x.checked ? _x000D_
              obj_x000D_
            : _x000D_
              null_x000D_
          :_x000D_
            obj_x000D_
        )(_x000D_
          {_x000D_
            [x.name]:x.value_x000D_
          }_x000D_
        )_x000D_
      )_x000D_
    ).filter(x => x)_x000D_
  );_x000D_
}_x000D_
_x000D_
function whenSubmitted(e) {_x000D_
  e.preventDefault()_x000D_
  console.log(_x000D_
    JSON.stringify(_x000D_
      serializeIt(document.forms[0]),_x000D_
      4, 4, 4_x000D_
    )_x000D_
  )_x000D_
}
_x000D_
<form onsubmit="whenSubmitted(event)">_x000D_
<input type=text name=hiThere value=nothing>_x000D_
<input type=radio name=okRadioHere value=nothin>_x000D_
<input type=radio name=okRadioHere1 value=nothinElse>_x000D_
<input type=radio name=okRadioHere2 value=nothinStill>_x000D_
_x000D_
<input type=checkbox name=justAcheckBox value=checkin>_x000D_
<input type=checkbox name=justAcheckBox1 value=checkin1>_x000D_
<input type=checkbox name=justAcheckBox2 value=checkin2>_x000D_
_x000D_
<select name=selectingSomething>_x000D_
<option value="hiThere">Hi</option>_x000D_
<option value="hiThere1">Hi1</option>_x000D_
<option value="hiThere2">Hi2</option>_x000D_
<option value="hiThere3">Hi3</option>_x000D_
</select>_x000D_
<input type=submit value="click me!" name=subd>_x000D_
</form>
_x000D_
_x000D_
_x000D_


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

Please try to change the code as below:

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

     const elements = Array.from(e.currentTarget) as HTMLInputElement[];

     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>

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

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

_x000D_
_x000D_
// 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();
}
_x000D_
<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>
_x000D_
_x000D_
_x000D_


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.


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


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;

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


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.


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

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

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