Brigo
Brigo

Reputation: 1112

Pushing all the values of an input class into an array

Based on what I learned and what I read here on Stack as well, I wrote a code that should get all the values of a specified class of input and pushing them into an array.

What I think this jQuery sript should do is:

The problem is that anything is displayed in the console, as nothing happened, so I guess there's a conceptual/writing error.

jQuery :

$(document).ready(function(){

    var myArray = [];
    $('#subButton').on('click', function() {
        $('.req').each(function() {
            myArray.push($(this).val()); 
            console.log(myArray);
        });
    });     

});

HTML :

<form id="iForm">
  <input type="text" id="i1" class=".req" placeholder="Name">
  <input type="text" id="i2" placeholder="Surname">
  <input type="text" id="i3" placeholder="Text A">
  <input type="text" id="i4" class=".req" placeholder="Text B">

  <input type="button" id="subButton" value="Registrati">
</form>

Upvotes: 3

Views: 4034

Answers (2)

Alnitak
Alnitak

Reputation: 339816

Having fixed your class attributes to remove the leading period character, you can use:

var myArray = $('.req').get().map(function(el) { return el.value });

Where $(...).get() converts the jQuery collection into a standard array, and .map extracts the field values.

This is somewhat cleaner than using .each with a push.

Upvotes: 2

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

You've to remove the . before the classes in your HTML inputs :

<input type="text" id="i1" class=".req" placeholder="Name">
__________________________________^
<input type="text" id="i4" class=".req" placeholder="Text B">
__________________________________^

Should be :

<input type="text" id="i1" class="req" placeholder="Name">
<input type="text" id="i4" class="req" placeholder="Text B">

Hope this helps.

$(document).ready(function(){

  var myArray = [];
  $('#subButton').on('click', function() {
    $('.req').each(function() {
      myArray.push($(this).val()); 
      console.log(myArray);
    });
  });     

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="iForm">
  <input type="text" id="i1" class="req" placeholder="Name">
  <input type="text" id="i2" placeholder="Surname">
  <input type="text" id="i3" placeholder="Text A">
  <input type="text" id="i4" class="req" placeholder="Text B">

  <input type="button" id="subButton" value="Registrati">
</form>

Upvotes: 3

Related Questions