Read multiple jQuery.val() into array

徘徊边缘 提交于 2019-12-31 19:14:06

问题


I have some code that looks like this that works just fine:

var info = [];
for (i = 0; i < 10; i++)
{
     info[i] = $('#info_' + i).val();
}

The problem is that this pattern is very common in my application with some minor variations. What i would like to do is to make this into a oneliner something like this where info becomes an array:

var info = $('[id^="info_"]').each().val();

回答1:


Found a solution thanks to Dogbert. All that was missing in his example was the .get()

Here is the solution i ended up using:

var info = $('[id^="info_"]').map(function () { return $(this).val(); }).get();



回答2:


You can use jQuery.map

var info = $('[id^="info_"]').map(function() { return $(this).val(); } )



回答3:


$('[id^="info_"]').each(function(){ info.push($(this).val()); });

should do



来源:https://stackoverflow.com/questions/6452902/read-multiple-jquery-val-into-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!