Accessing FormData Values

后端 未结 11 822
误落风尘
误落风尘 2020-12-08 07:48

I have a FormData object which I create in javascript from an HTML form like so. The FormData object doesn\'t seem very well documente

相关标签:
11条回答
  • 2020-12-08 07:51

    My solution with for-of

    const formData = new FormData(document.getElementById('form'))
    
    for (const [key, value] of formData) {
      console.log('»', key, value)
    }
    
    0 讨论(0)
  • 2020-12-08 07:53

    A simple HTML5 way (form to object) using the runarberg/formsquare library (npm i --save formsquare):

    import formsquare from "formsquare";
    
    const valuesObject = formsquare.filter((el) => !el.disabled).parse(document.getElementById('myForm'));
    //=> {"foo": "bar"}
    

    https://github.com/runarberg/formsquare

    0 讨论(0)
  • 2020-12-08 07:57

    Just to add to the previous solution from @Jeff Daze - you can use the FormData.getAll("key name") function to retrieve all of the data from the object.

    0 讨论(0)
  • 2020-12-08 07:58

    it will work

    let form = document.querySelector("form");
    let data = new FormData(form)
    formObj = {};
    for (var pair of data.entries()) {
      formObj[pair[0]] = pair[1]
    }
    console.log(formObj)

    0 讨论(0)
  • 2020-12-08 08:02

    First thing I don't think it's possible to build a FormData object from a form as you've specified, and to get values from the form use the method described in the accepted answer -- this is more of an addendum!

    It looks like you can get some data out of a FormData object:

    var formData = new FormData();
    formData.append("email", "test1@test.com");
    formData.append("email", "test2@test.com");
    formData.get("email");
    

    this will only return the first item for that key, in this case it will return 'test1@test.com', to get all the email addresses use the below code

    formData.getAll("email")
    

    Please see also: MDN article on formdata get method.

    0 讨论(0)
  • 2020-12-08 08:04

    Another solution:
    HTML:

    <form>
    <input name="searchtext"  type="search" >'
    <input name="searchbtn" type="submit" value="" class="sb" >
    </form>
    

    JS:

    $('.sb').click( function() {
        var myvar=document.querySelector('[name="searchtext"]').value;
        console.log("Variable value: " + myvar);
    });
    
    0 讨论(0)
提交回复
热议问题