Вопрос

Hey all i am trying to figure out a way to add the data to a JS object when i loop to see which checkboxes on the page are checked:

jQuery('#doaction').click(function () {
    var bulkSelected = jQuery('#bulkAction').val();
    var checkCount = 1;

    if (bulkSelected == 0) {
        console.log('no bulk selected category');
        jQuery('#overlay-shade').fadeOut(300);
    } else {
        var doBulk = {
            called: '' + bulkSelected + '',
        };

        jQuery('input[type=checkbox]').each(function () {                           
            if (jQuery(this).attr('id') != 'selectAll') {
                var isChecked = (this.checked ? true : false);

                if (isChecked == true) {
                    console.log(jQuery(this).attr('id'));
                    console.log(jQuery(this).attr('data-accnum'));
                }
                checkCount++;
            }
        });

    }

the .attr('data-accnum') has the number as you see below. I need it to be in this format:

(checkbox name: accnum)

var doBulk = {
    chk1: 52136523168,
    chk2: 54298851631
    ect..ect...
};

How can i do that?

Это было полезно?

Решение

Try:

var doBulk = {};
jQuery('input[type=checkbox]').each(function () {                           
    if (jQuery(this).attr('id') != 'selectAll') {
        var isChecked = (this.checked ? true : false);

        if (isChecked == true) {
            doBulk[jQuery(this).attr('id')] = +jQuery(this).attr("data-accnum");
        }
        checkCount++;
    }
});
console.log(doBulk);

Другие советы

jQuery has a :checked selector, as well as a not method which we use to only get all checked inputs that are not #selectAll.

Then you just add it to the doBulk object using bracket notation, accessing the doBulk object from within the each function is possible because javascript has closures.

    var doBulk = {}
      , checked = jQuery('input[type=checkbox]:checked').not('#selectAll')
      , checkCount = checked.length;

    checked.each(function () {                           
      doBulk[this.id] = jQuery(this).attr('data-accnum');
    });
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top