FeelRightz
FeelRightz

Reputation: 2979

Jquery foreach function

Im trying to foreach array and assign the array data into each checkbox, I found out Jquery have a each function able to do that. Bellow jsfiddle is what Im tried so far. But I not sure why it only came out 1 checkbox ,should be 4 checkbox with correct value, anyone can help me check my code ? what mistake that I have made , Thanks so much .

JS Fiddle

HTML

 <div id="popupfoot"></div>

JS

    var PG = {
    divid:"",
    multiselection:"",
    optionitem:[],        
    init:function(divid,multiselection,optionitem){
       PG.divid = divid;
       PG.multiselect = multiselection;
       PG.optionitem = optionitem;
       PG.render();
    },
    test:function(){
        for(var i =0; PG.optionitem.length > i ; i++){
            alert(PG.optionitem[i].name);
        }
    },
    render:function(){
/*      for(var i =0; PG.optionitem.length > i ; i++){*/

        $.each(array, function(i,obj) {
        var fruit = "<div class='fruit'>" +
                        "<input class='the_checkbox' type='checkbox' id="+obj.value+" name="+obj.name+" value="+obj.value+">" +
                        "<label class='label' for="+obj.value+">"+obj.value+"</label>" +
                      "</div>";


                    $("#"+PG.divid).html(fruit);
                    $('.the_checkbox').on('change', function(evt) {
                       if($(this).siblings(':checked').length >= PG.multiselect) {
                           this.checked = false;
                       }
                    });           
        });
/*      }*/



    },
    save:function(){
    }
}


var array = [];
array[0] = {"name":"fruit","value":"mango"};
array[1] = {"name":"fruit","value":"apple"};
array[2] = {"name":"fruit","value":"orange"};
array[3] = {"name":"fruit","value":"banana"};

PG.init("popupfoot", "1", array);
PG.render(); 

Upvotes: 0

Views: 159

Answers (2)

TSKSwamy
TSKSwamy

Reputation: 225

Required two changes:

1.Change the $("#"+PG.divid).html(fruit); to $("#"+PG.divid).append(fruit);

2.//PG.render(); // as you are already calling it in init;

Updated Fiddle

http://jsfiddle.net/1wskk51m/2/

Upvotes: 1

Domain
Domain

Reputation: 11808

Your code is overwriting the the div content instead of appending.

Replace

$("#"+PG.divid).html(fruit);

with following line

$("#"+PG.divid).append(fruit);

Upvotes: 1

Related Questions