Comma separated list in jQuery

前端 未结 4 1344
后悔当初
后悔当初 2021-02-05 08:01

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.leng         


        
4条回答
  •  温柔的废话
    2021-02-05 08:30

    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"
    

提交回复
热议问题