Phi*_*enn 19 html checkbox jquery serialization
我正在尝试从表单上检查的内容创建逗号分隔列表.
var $StateIDs = $(':checked');
var StateIDs = '';
for (i=0, j = $StateIDs.length; i < j; i++) {
StateIDs += $StateIDs[i].val();
if (i == j) break;
StateIDs += ',';
}
Run Code Online (Sandbox Code Playgroud)
可能有一个可以做到这一点的单线程,或单个功能.
Joh*_*ler 60
map()将成为你的朋友.
var StateIDs = $(':checked').map(function() {
return this.value;
}).get().join(',');
Run Code Online (Sandbox Code Playgroud)
StateID将是逗号分隔的字符串.
一步一步 - 发生了什么?
$(':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"
Run Code Online (Sandbox Code Playgroud)