Show form name = value pairs in console with vanilla JavaScript?

I've tried over a dozen solutions, none of them are just letting me do

console.log(name + " " + value);

without some kind of wonky JavaScript thing I'm not seeing how to do (I get like 90% of everything in different combinations)... I need to get inputs and selects and textareas, even preferably hiddens, everything you would type or click on a typical form (except for file upload).

2 answers

  • answered 2018-11-08 00:51 hev1

    You can use the FormData constructor, passing in the form that you want the key-value pairs of. If you pass in the form as an argument, it will automatically contain the form's current key/value pairs (the key being the name of the elements and the value being their value). File input content will also be encoded, making it ideal for AJAX calls.

    var formData = new FormData(document.getElementById("myForm"));
    console.log(...formData);
    <form id="myForm" name="myForm">
      <div>
        <label for="username">Enter name:</label>
        <input type="text" id="username" name="username"value="John">
      </div>
      <div>
        <label for="useracc">Enter account number:</label>
        <input type="text" id="useracc" name="useracc" value="123456">
      </div>
    <input type="submit" value="Submit!">
    </form>

    If you want all of the key/value pairs inside an Object, you could loop through all of the elements inside the form with a name attribute present to set the property of the Object equal to the name of the element to the value of the element.

    var formMap = {};
    var formElems = document.querySelectorAll('#myForm [name]');
    for(var i = 0; i < formElems.length; i++){
      var elem = formElems[i];
      formMap[elem.name] = elem.value;
    }
    console.log(formMap);
    //now you can get the values of the form element with a particular name like so:
    //formMap["username"];->"John"
    <form id="myForm" name="myForm">
      <div>
        <label for="username">Enter name:</label>
        <input type="text" id="username" name="username"value="John">
      </div>
      <div>
        <label for="useracc">Enter account number:</label>
        <input type="text" id="useracc" name="useracc" value="123456">
      </div>
    <input type="submit" value="Submit!">
    </form>

  • answered 2018-11-08 00:53 Dacre Denny

    A simple solution via querySelectorAll is possible. You could select all descendants of form elements that have name attributes, and then iterate the result, logging each element to console, like so:

    document.body
    .querySelectorAll('form [name]')
    .forEach(element => {
    
       console.log('name:', element.name, 'value:', element.value);
    })
    <form>
      <input name="name" value="bob" />
      <input name="age" value="30" />
    </form>