简体   繁体   中英

Get all form values into javascript array

I am attempting to get all the form values into a normal array[]. I had it working for tags but then I added some tags and can't seem to get it.

With just tags it worked with this

var content = document.querySelectorAll("#form input[name='content[]']");

I am currently trying something like this

var content = document.elements["content[]"].value;

This form can change from user input down the road as each section of the form is a module that they choose to add. It is also important to get the values in order, if that isn't possible then I would need to make it a JSON array. Pure javascript or jquery is fine either way.

Thank you for any help.

EDIT

I used this to solve my problem

  var contents=[]
  var content = $('#form').serializeArray()
  for (var i = 0; i < content.length; i++) {
    contents[contents.length]=content[i].value
  };

Try

html

<form id="form">
    <input type="text" name="content[]" value="abc" />
    <textarea name="textarea" value="">123</textarea>
</form>

js

$(function() {
  var form = $("#form");
    // escape `[]`
    var content = form.find("input[name=content\\[\\]]");
    // array `literal declaration` 
    var _arr = [content.prop("value")];
    // map all form values to single array
    var arr = $.map(form.serializeArray(), function(v, k) {
      return [v.value]
    });
    // array literal with `textarea` `value`
    var t = [$("textarea").prop("value")];
    console.log(_arr, arr, t); 
    // _arr: `["abc"]` , arr:`["abc", "123"]` t:`["123"]` 
})

Demo .

See Arrays

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM