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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With