Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all form values by JavaScript

I have form:

<form onchange="allvaluestostring()">
    <select name="status">
         <option value="*">All</option>
         <option value="1">Active</option>
         <option value="0">Inactive</option>
    </select>
    <select name="size">
          <option value="*">All</option>
          <option value="small">Small</option>
          <option value="big">Big</option>
    </select>
</form>

And the onchange action of any input in form I need to get a JavaScript string, for example "status=1&size=big" for using in httprequest.

Does there exist something in JavaScript that will take all form values when one of form inputs will be changed?

I used <select name="status" onchange="showExporteditems(this.name,this.value)">, but this will take only one input value for using only "status=1", but I need on each onchage all values from all inputs for string like "status=1&size=big&...etc....".

Without using jQuery.

like image 544
Martin Avatar asked Apr 17 '14 17:04

Martin


2 Answers

2021 version (TypeScript)

  const onSubmit = (e: any) => {
    e.preventDefault();
    const form = e.target as HTMLFormElement;
    const values = Object.fromEntries(
      Array.from(form.elements).map((x: Element) => {
        const input = x as HTMLInputElement;
        console.log(input);
        return [input.name ?? input.id, input.value];
      })
    );
    console.log(values);
  };
like image 50
Slawa Avatar answered Sep 21 '22 09:09

Slawa


For input fields you could use ECMAScript 6 like the following:

Get your form in a constant:

const form = document.querySelector('form')

Grab all values:

Object.values(form).reduce((obj,field) => { obj[field.name] = field.value; return obj }, {})

The above snippet will produce an object with the input name as the key and its value.

like image 27
Shairon Toledo Avatar answered Sep 22 '22 09:09

Shairon Toledo