简体   繁体   中英

Meteor: How to set a number based on the number of checked boxes within a section

I currently have a multi-section form, with a number of checkboxes. What Im trying to do, is show the number of checked boxes, next to the total. I have total showing up just fine, but I cant for the life of me figure out a way to loop over the inputs, successfully find the :checked, and print that number out.

I think the main thing causing me issues, is that it needs to update every time a new box is checked. Heres some of the code.

Event Handler

'click input[type=checkbox]': function(){
    Session.set('selectedPlayerCount', n);
    Session.get('selectedPlayerCount');
}

The goal here is to set the number of selected players, and pass it to the template/helper.

Helper

countSelected: function(){
    n = 0;
    n++;
    var selectedPlayerCount = Session.get('selectedPlayer');
    return selectedPlayerCount;
}

Within the helper I'm attempting to iterate every time the event is triggered, and as a result increase the value by one. I'm aware that resetting n back to 0 is going to cause some issues, and I know that needs to be changed one the rest is figured out. I just cant figure out where the variable needs to be set in order to provide a default value.

Template

<header>
   <p>{{ countSelected }}</p>
</header>

All I'm trying to do here for now is to print out the value rendered by the helper. I don't believe this is causing any issues.

TL;DR - How to count number of checked inputs within a section of a form, and for each one, increment a value, and then return it every time its changed.

I'm new to this but maybe this will serve: define your account to zero in a session variable, each time you select a checkbox you increase the value of your session variable

Session.set("countPlayersChecked", 0);
Template.proof.helpers({
    countSelected: function () {
        return Session.get("countPlayersChecked");
    }

});

Template.proof.events({
    'click input[type=checkbox]': function (event) {

        if($(event.target).is(':checked'))
            Session.set("countPlayersChecked", Session.get("countPlayersChecked")+1);
        else
            Session.set("countPlayersChecked", Session.get("countPlayersChecked")-1);
    }
});

Hope it serves.

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