Taking multiple equal input values and storing in an array with Javascript/jQuery

Asked

Viewed 870 times

1

inserir a descrição da imagem aqui

I got this div, that’s <div class='pergunta'>, inside of her I have <input type='text'> <select></select> <input type='checkbox'> The point is that this entire div can repeat itself if I click add new question, that is, I can have 1 or N Divs that contain these same fields, I need to make a Javascript/jQuery script that takes the value of each field and stores it in an array, for example, I have two <div class'pergunta'> with these fields, I need to add the values of each field in an array for example:

var array = [{titulo: , tipo: , requerido: }, {titulo: , tipo: , requerido: }]

That is, how do I add the values of these fields from each div into an array?

1 answer

0


Creates a selector that picks up all <div class='pergunta'> and then do a mapping to get the values of the title and type.

An example would be like this:

const arr = $('.pergunta').map(function() {
  return {
    titulo: this.querySelector('input[type="text"]').value,
    tipo: this.querySelector('select').value,
    requerido: this.querySelector('input[type="checkbox"]').checked
  }
}).get();
console.log(arr);
  • It worked!! The problem is that when I try to send this 'arr' via ajax, POST method, it is returning me the following error: "Uncaught Typeerror: Illegal Invocation".

  • @Leonardotheodoro, use it .get() at the end to turn into a native array instead of jQuery collection.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.