简体   繁体   English

使多个输入字段值的javaScript / jQuery数组

[英]Make javaScript/jQuery array of multiple input field values

Simple question i can't figure out. 我不知道一个简单的问题。 I'd like to make a JavaScript array of input values but can't figure out the simple code. 我想制作一个包含输入值的JavaScript数组,但无法弄清楚简单的代码。

Here's the HTML: 这是HTML:

<input class="email" value="joe@smith.com"></input>
<input class="email" value="bob@jones.com"></input>

Here's the not yet correct JS/jQuery which attempts to make an array: 这是尚未正确的JS / jQuery,它试图创建一个数组:

$.fn.valuesArr = function()
  {
    var a = [];
    $.each(this, function(i, field){
        a.push(field.value);
    });
    return a;
  } 

var emailArr=$('.email').valuesArr();

Ultimately, this is what i'd like the emailArr to be: 最终,这就是我希望的emailArr为:

emailArr= ["joe@smith.com", "bob@jones.com"];

Not sure what is wrong with my valuesArr function, any JS and/or jQuery-based solution would be greatly appreciated! 不知道我的valuesArr函数出了什么问题,将不胜感激任何基于JS和/或jQuery的解决方案!

This should get all the elements of class email it value and then assign it to the email array. 这应该获取类email值的所有元素,然后将其分配给email数组。

$("action").click(function () {
    var emails=new Array();
    var j=0;
    $(".email").each(function(){
        emails[j]=$(this).val();
        j++;
    });
});

The original script was correct as Pat said. 如Pat所说,原始脚本是正确的。 The problem was with how the script was called. 问题在于脚本的调用方式。 The original script will work if you do either of the following: 如果执行以下任一操作,则原始脚本将起作用:

  1. making sure the original script is below the tags in your your HTML file 确保原始脚本在HTML文件中的标签下方
  2. encapsulating the script in a jQuery document.ready function, ie, $(function(){ --$.each function() -- }); 将脚本封装在jQuery document.ready函数中,即$(function(){-$。each function()-});

Thanks to both Pat and COLD TOLD for their help, 感谢Pat和COLD TOLD的帮助,

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

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