Comma separated list in jQuery

2020-05-25 06:22发布

I'm trying to create a comma separated list from what is checked on the form.

var $StateIDs = $(':checked');
var StateIDs = '';
for (i=0, j = $StateIDs.length; i < j; i++) {
    StateIDs += $StateIDs[i].val();
    if (i == j) break;
    StateIDs += ',';
}

There's probably a 1-liner that can do this, or a single function.

4条回答
Anthone
2楼-- · 2020-05-25 06:53

Check the second answer here. It gives you nicely simplified code for exactly what you're doing.

查看更多
再贱就再见
3楼-- · 2020-05-25 06:55
$.each([52, 97], function(index, value) { 
  alert(index + ': ' + value); 
});
查看更多
你好瞎i
4楼-- · 2020-05-25 07:02

map() is going to be your friend here.

var StateIDs = $(':checked').map(function() { 
    return this.value; 
}).get().join(',');

StateIDs will be a comma-separated string.


Step-by-step - What is going on?

$(':checked')
// Returns jQuery array-like object of all checked inputs in the document
// Output: [DOMElement, DOMElement]

$(':checked').map(fn);
// Transforms each DOMElement based on the mapping function provided above
// Output: ["CA", "VA"]  (still a jQuery array-like object)

$(':checked').map(fn).get();
// Retrieve the native Array object from within the jQuery object
// Output: ["CA", "VA"]

$(':checked').map(fn).get().join(',');
// .join() will concactenate each string in the array using ','
// Output: "CA,VA"
查看更多
啃猪蹄的小仙女
5楼-- · 2020-05-25 07:04
var ids = '';
$(':checked').each(function(){
    ids += $(this).val() + ',';
});

Writing blind, so I have not tested.

查看更多
登录 后发表回答