Get checkbox list values with jQuery

后端 未结 8 1857
抹茶落季
抹茶落季 2020-12-13 18:35

In a div, I have some checkbox. I\'d like when I push a button get all the name of all check box checked. Could you tell me how to do this ?

8条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-13 18:42

    Since nobody has mentioned this..

    If all you want is an array of values, an easier alternative would be to use the .map() method. Just remember to call .get() to convert the jQuery object to an array:

    Example Here

    var names = $('.parent input:checked').map(function () {
        return this.name;
    }).get();
    
    console.log(names);
    

    var names = $('.parent input:checked').map(function () {
        return this.name;
    }).get();
    
    console.log(names);
    
    

    Pure JavaScript:

    Example Here

    var elements = document.querySelectorAll('.parent input:checked');
    var names = Array.prototype.map.call(elements, function(el, i) {
        return el.name;
    });
    
    console.log(names);
    

    var elements = document.querySelectorAll('.parent input:checked');
    var names = Array.prototype.map.call(elements, function(el, i){
        return el.name;
    });
    
    console.log(names);

提交回复
热议问题