jQuery 获取与数组具有相同类的所有输入的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19247727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:31:45  来源:igfitidea点击:

Get the values of all inputs with same class as an array

jquery

提问by kwk.stack

I have a group of inputs and I want to get the value of each one in array form or in any way that you will suggest. I am not very good at arrays.

我有一组输入,我想以数组形式或您建议的任何方式获取每个输入的值。我不太擅长数组。

$(elemnt).each(function(index, element) {
    $('#spc-name').val($(".spocName").val());
    alert($(".spocName").val());
});

the above line of code alert right thing for me but for a single input only but I have multiple inputs with class="spocName"so I want to get values of all and so that I could then save each in DB table in seperate rows.

上面的代码行提醒我正确的事情,但仅适用于单个输入,但我有多个输入,class="spocName"因此我想获取所有值,以便我可以将每个值保存在单独的行中的 DB 表中。

回答by AbhinavRanjan

If all your inputs share the same class say "class1" then you can select all such inputs using this

如果您的所有输入共享同一个类,例如“class1”,那么您可以使用此选项选择所有此类输入

var inputs = $(".class1");

Then you can iterate over the inputs any way you want.

然后你可以以任何你想要的方式迭代输入。

for(var i = 0; i < inputs.length; i++){
    alert($(inputs[i]).val());
}

回答by Rory McCrossan

To get the values of each element as an array you can use map():

要将每个元素的值作为数组获取,您可以使用map()

var valueArray = $('.spocName').map(function() {
    return this.value;
}).get();

Or in ES6 (note that this is unsupported in IE):

或者在 ES6 中(请注意,这在 IE 中不受支持):

var arr = $('.spocName').map((i, e) => e.value).get();

You can then use this array as required to save to your database - eg. as a parameter in an AJAX request.

然后您可以根据需要使用这个数组来保存到您的数据库 - 例如。作为 AJAX 请求中的参数。

回答by LeGEC

var values = [];
$('.spocNames').each(function(){
    values.push({ name: this.name, value: this.value }); 
});
//use values after the loop
console.log(values);

回答by Mandip Darji

you can user jquery eachfunction ...

您可以使用 jquery每个功能...

$('.spocNames').each(function(){
  alert(this.value);
}