Getting value of multiple input fields with same class and adding into javascript object

html, javascript, jquery

Solution

There is no problem with your Code. And I would suggest you to write it as utility method

function getValues(selector){
  var tempValues = {};
  $(selector).each(function(){
     var th= $(this);
     tempValues[th.attr('title')] = th.val();
   });
  return tempValues;
}

var values = getValues('.email');

or If you want values into an array

$('.email').map( function(){return $(this).val(); }).get();

`.get()` will convert it to a regular array.

The code you have written is absolutely correct. But when I have loaded it was returning me null, because at the time of execution, there were no values in textboxes.

Problem

I am faced with a issue as follows: ``` <input title="1" type="text" class="email"> <input title="2" type="text" class="email"> <input title="3" type="text" class="email"> ``` Above is my html where I am trying to grab the emails of each input box and store it in an object with the title as key. Here is what my JavaScript currently looks like ``` var emailObj = {}; $("input[class=email]").each(function() { var id = $(this).attr("title"); var email = $(this).val() emailObj[id] = email; }); ``` Currently console.log displays only the last value added to the object as shown below. ``` Object { 3="a@a.com"} ``` Where my expected result should be as show below ``` Object { 1="a@a.com", 2="b@b.com", 3="c@c.com"} ``` Could someone shed some light on this issue for me please? Thank you for reading, Regards.

Original source