简体   繁体   中英

How can I create a JSON object by getting checkboxes names and values?

I'm building a script to update the url based on the checkboxes that the user selects. I found a interesting script that handles the update thing but I need to construct an object like this:

Object {foo: "bar", spam: "eggs", tracker: "yes"}

I already get the checkboxes values and push them into an array, but I don't know how to build an object similar to the above

My array looks like this in the console:

["brand:Brand3", "brand:Brand5", "size:Size1"]

This is my jsfiddle (see the output in the browser's console)

Any help is greatly appreciated.

One way:

$('input[type="checkbox"]').on('change', function () {
    var url = document.URL;
    var addition = {};
    $('input').each(function(){
      addition[$(this).prop('name')] = $(this).val();
    });
    console.log(JSON.stringify(addition));
})

Js Fiddle

You might need to change the selector, depending if you have more inputs on the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM