lundi 26 octobre 2015

Meteor checkbox group - only one checkbox checked at a time like a radio

I've accomplished to create a checkbox group where at least one checkbox has to be checked. Now i want to go a step further and let the checkbox group behave like a group of radio buttons, so that only one checkbox can be selected at a time and at least one has to be selected.

The code so far:

HTML:

<form>
    <ul>
        {{#each checkbox}}
        <li>
            <input type="checkbox" checked="{{checked}}" class="toggle-checked"> {{name}}: {{checked}}
        </li>
        {{/each}}
    </ul>
</form>

JS:

Cbtest = new Mongo.Collection('cbtest');

Template.checkbox.helpers({
    checkbox: function () {
        return Cbtest.find();
    }
});

Template.checkbox.events({
    "click .toggle-checked": function (event) {
        var self = this;
        //deactivate the checkboxes visually
        event.preventDefault();
        Meteor.call("setChecked", self._id, !self.checked);
    }
});

Meteor.methods({
    setChecked: function (checkboxId, setChecked) {
        //deactivate the checkbox value change in the database
        if (!setChecked && CheckboxResources.find({
            checked: true
        }).count() === 1)
        return;
        Cbtest.update(checkboxId, {
            $set: {
                checked: setChecked
            }
        });
    }
});

Thanks in advance for your help!

Vin




Aucun commentaire:

Enregistrer un commentaire