简体   繁体   English

获取具有相同类的多个输入字段的值并添加到javascript对象中

[英]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. 上面是我的html,我试图抓取每个输入框的电子邮件并将其存储在标题为关键字的对象中。

Here is what my JavaScript currently looks like 这是我的JavaScript目前的样子

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. 目前console.log仅显示添加到对象的最后一个值,如下所示。

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. 谢谢你的阅读,问候。

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. .get()会将其转换为常规数组。

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. 但是当我加载它时,它返回null,因为在执行时,文本框中没有值。

Your taskArray is actually an object , not an array. 您的taskArray实际上是一个对象 ,而不是一个数组。

Replacing var taskArray = {} with this should fix the problem: 用这个替换var taskArray = {}可以解决问题:

var taskArray = new Array();

Edit: on second thoughts, what you have already is perfectly valid! 编辑:第二个想法,你已经完全有效!

I'm editing my answer to echo what I've said in the comments: you'll need to debug using the console: 我正在编辑我的回答以回应我在评论中所说的内容:您需要使用控制台进行调试:

Within the .each() , put: console.log(id); .each() ,put: console.log(id); - the expected result would be "1", "2", "3" - if it's just "3", it probably means that your other inputs aren't being picked up for whatever reason. - 预期结果将是“1”,“2”,“3” - 如果它只是“3”,则可能意味着您的其他输入因任何原因未被提取。 If that is the result, print out the object after you've assigned the value: console.log(emailObj[id]); 如果这是结果,请在分配值后打印出对象: console.log(emailObj[id]); .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM