Skip to content
Advertisement

Get control attributes with jQuery and create json

I have multiple checkboxes in a view and each one has some data attributes, example:

enter image description here

Once the button is clicked I’m iterating through all the checkboxes which are selected and what I want to do is get the data-price and value fields for each selected checkbox and create JSON array.

This is what I have so far:

var boxes2 = $("#modifiersDiv :checkbox:checked");
            var selectedModifiers = [];
            var modifierProperties = [];
            for (var i = 0; i < boxes2.length; i++) {

                for (var k = 0; k < boxes2[i].attributes.length; k++) {
                    var attrib = boxes2[i].attributes[k];
                    if (attrib.specified == true) {
                        if (attrib.name == 'value') {
                            modifierProperties[i] = attrib.value;
                            selectedModifiers[k] = modifierProperties[i];
                        }
                        if (attrib.name == 'data-price') {
                            modifierProperties[i] = attrib.value;
                            selectedModifiers[k] = modifierProperties[i];
                        }                 
                    }                    
                }
            }
            var jsonValueCol = JSON.stringify(selectedModifiers);

I’m not able to get the values for each checkbox and I’m able to get the values only for the first one and plus not in correct format, this is what I’m getting as JSON:

[null,"67739",null,"1"]

How can I get the correct data?

Advertisement

Answer

You can use $.each to parse a jquery array, something like:

var jsonValueObj = [];
$("#modifiersDiv :checkbox:checked").each(function(){
  jsonValueObj.push({'value':$(this).val(),'data-price':$(this).attr('data-price')});
});
jsonValueCol = JSON.stringify(jsonValueObj);

Please note it’s generally better to use val() than attr(‘value’). More information on this in threads like: What’s the difference between jQuery .val() and .attr(‘value’)?

As for your code, you only had one answer at most because you were overwriting the result every time you entered your loop(s). Otherwise it was okay (except the formatting but we’re not sure what format you exactly want). Could please you provide an example of the result you would like to have?

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement