Category checkboxes

by Csaba Hellinger

HTML

<form id="category-form">
    <input type="checkbox" data-id="1">1</input>
    <input type="checkbox" data-id="2">2</input>
    <input type="checkbox" data-id="3">3</input>
    <input type="checkbox" data-id="4">4</input>
    <input type="checkbox" data-id="5">5</input>
    <input type="checkbox" data-id="6">6</input>
</form>

<br>
String: <span id="categories"></span>

CSS

#categories {
    font-family: monospace;
    font-size: 1.5em;
}

JavaScript

var categories = [];

// check all at first
$('#category-form input').each(function () {
    this.checked = true;
    categories.push($(this).attr('data-id'));
});
update();

// on change
$('#category-form input').change(function () {
    var id = $(this).attr('data-id'),
        index = categories.indexOf(id);
      
    // add / remove
    if (this.checked && index === -1) {
        categories.push(id);
    } else if (!this.checked && index !== -1) {
        categories.splice(index, 1); 
    }

    // at least one
    if (categories.length === 0) {
        this.checked = true;
        categories.push(id);
    }

    update();    
});

// convert to string    
function update() {
    $('#categories').text(categories.join('%2C'));
}