jquery - javascript dynamically add values to array - Stack Overflow

I'm trying to loop over the checkboxes in a form and add their values to a multidimensional javasc

I'm trying to loop over the checkboxes in a form and add their values to a multidimensional javascript object. The 'attrib' data attribute will be the key. Possible key values are 'category', 'product_group' and 'language' but I'd rather add them dynamically in case any more get added in the future.

I want to end up with an object like this, which I can easily send as a json_encode 'd single value to the server.

values = {
    'category' : {1,2,3},
    'product_group' : {4,5,6},
    'language': {'en','fr','de'}
};

Code below. Here obviously each iteration overwrites existing values instead of adding to it. I'm unsure where I can create values[key] as an object ... ?

$('.filter input, .multiselect-container input').change(function() {
    var values = {}
    $('.filter input:checked').each(function() {
        if($(this).is(':checked')) {
            var key = $(this).data('attrib')
            var value = $(this).val()
            values[key] = value
            // values[key].push(value) = calling method push of undefined ...
        }
        else {
            // Remove value
        }       
    })
    console.log(values) 
})

I'm trying to loop over the checkboxes in a form and add their values to a multidimensional javascript object. The 'attrib' data attribute will be the key. Possible key values are 'category', 'product_group' and 'language' but I'd rather add them dynamically in case any more get added in the future.

I want to end up with an object like this, which I can easily send as a json_encode 'd single value to the server.

values = {
    'category' : {1,2,3},
    'product_group' : {4,5,6},
    'language': {'en','fr','de'}
};

Code below. Here obviously each iteration overwrites existing values instead of adding to it. I'm unsure where I can create values[key] as an object ... ?

$('.filter input, .multiselect-container input').change(function() {
    var values = {}
    $('.filter input:checked').each(function() {
        if($(this).is(':checked')) {
            var key = $(this).data('attrib')
            var value = $(this).val()
            values[key] = value
            // values[key].push(value) = calling method push of undefined ...
        }
        else {
            // Remove value
        }       
    })
    console.log(values) 
})
Share Improve this question edited Sep 2, 2013 at 13:02 Arturs 1,2545 gold badges21 silver badges28 bronze badges asked Sep 2, 2013 at 12:39 stefstef 27.8k31 gold badges107 silver badges143 bronze badges 1
  • Of course for a new values[key], that hasn’t been accessed so far, trying to call .push will fail, because there is no array to call that method on yet. So check first, if that element is an array already – if not, initialize it as a new array first, and then push the next value to it afterwards. – C3roe Commented Sep 2, 2013 at 12:45
Add a ment  | 

4 Answers 4

Reset to default 4

Your error is due to the fact that values[key] is undefined, therefore does not have a push method.

Try this code:

        if($(this).is(':checked')) {
            var key = $(this).data('attrib')
            var value = $(this).val()
            values[key] = values[key] || [] // initialize with empty array
            values[key].push(value)
        }

Not sure that's what you are looking for:

if(!values[key])
   values[key]=new Array();

values[key].push(value);

But this way you can add an array of value to every key.

Try this:

        if($(this).is(':checked')) {
            var key = $(this).data('attrib')
            var value = $(this).val()
            if(typeof values[key]  == "undefined")
            values[key] = [];
            values[key].push(value);

        }
        else {
            // Remove value
        }       

First, your data representation is not correct. The object attributes should be arrays like this:

values = {
    'category' : [1,2,3],
    'product_group' : [4,5,6],
    'language': ['en','fr','de']
};

With that data representation, this piece of code will do what you want:

$('.filter input, .multiselect-container input').change(function() {
var values = {}
$('.filter input:checked').each(function() {
    if($(this).is(':checked')) {
        var key = $(this).data('attrib')
        var value = $(this).val()
        values[key] = value
        if (values.key == undefined){
            //Check if key exists. If not, create it as an array
            values[key] = Array()
            values[key].push(value)
        }
        else{
            values[key].push(value)
        }
    }
    else {
        // Remove value
    }       
})
console.log(values) 

})

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745268472a4619601.html

相关推荐

  • jquery - javascript dynamically add values to array - Stack Overflow

    I'm trying to loop over the checkboxes in a form and add their values to a multidimensional javasc

    2小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信