Tauseef Hussain
Tauseef Hussain

Reputation: 1079

Generate json array with javascript

I am looking to generate a json string based on the button selection on a html page.

<div id="btnStudios" >
<button type="button" id="01" value="warner" class="btn btn-default">Warner</button>
<button type="button" id="02" value="tf1" class="btn btn-default">TF1</button>
<button type="button" id="03" value="gaumont" class="btn btn-default">Gaumont</button>
<button type="button" id="04" value="pathe" class="btn btn-default">Pathe</button>
<button type="button" id="05" value="studiocanal" class="btn btn-default">StudioCanal</button>
<button type="button" id="06" value="francetv" class="btn btn-default">FranceTV</button>
<button type="button" id="07" value="m6snd" class="btn btn-default">M6SND</button>
</div>

<div id = "btnplatforms" class="btn-group">
<button type="button" id = "11" value="orange" class="btn btn-default">Orange</button>
<button type="button" id = "12" value="itunes" class="btn btn-default">iTunes</button>
<button type="button" id = "13" value="sfr" class="btn btn-default">SFR</button>
</div>

$(".btn").click(function() {
$(this).toggleClass('active');
});

Based on the active state of the button i want the result to be for example {Studios : Warner, Gaumont Platform : Orange, iTunes}

Is this possible to achive this with javascript? If yes how? Thanks in advance for your help.

Upvotes: 4

Views: 117

Answers (2)

abdelouahed touimi
abdelouahed touimi

Reputation: 76

You can try this :

   var btn_active_array = {
    "Studios" : [],
    "Platform":[]
   };


   $('#btnStudios .btn.active').each(function(index,btn_active){
       btn_active_array["Studios"].push($(btn_active).text());
   });
   $('#btnplatforms .btn.active').each(function(index,btn_active){
       btn_active_array["Platform"].push($(btn_active).text());
   });

jsfiddle link : https://jsfiddle.net/5kb5fdyz/

Upvotes: 3

jcubic
jcubic

Reputation: 66650

You can try this:

var output = {
    Studios: $('#btnStudios button.active').map(function() {
        return $(this).val();
    }).get(),
    Platform: $('#btnplatforms button.active').map(function() {
        return $(this).val();
    }).get()
};

here is jsFiddle.

Upvotes: 2

Related Questions