sdla4ever
sdla4ever

Reputation: 128

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

Upvotes: 0

Views: 1616

Answers (1)

guest271314
guest271314

Reputation: 1

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

Upvotes: 1

Related Questions