Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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="[email protected]"}

Where my expected result should be as show below

Object { 1="[email protected]", 2="[email protected]", 3="[email protected]"}

Could someone shed some light on this issue for me please?

Thank you for reading, Regards.

like image 688
BaconJuice Avatar asked Jan 14 '23 03:01

BaconJuice


1 Answers

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.

like image 150
Exception Avatar answered Jan 16 '23 20:01

Exception