Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout.js Checkbox checked and click event

We're trying to implement a checkbox and list with the following functionality:

  • Clicking the checkbox will either clear the array if there are items in there, or add a new item if not.
  • Remove an item from the array when clicking the Remove button, once the last item is removed the checkbox automatically unchecks itself.

The problem I am having is that if you click to remove each array item, then click the checkbox to add a blank entry, I'm expecting the checkbox to be checked again (as per the checked observable), however it is not?

I have the following code:

http://jsfiddle.net/UBsW5/3/

    <div>
        <input type="checkbox" data-bind="checked: PreviousSurnames().length > 0, click: $root.PreviousSurnames_Click" />Previous Surname(s)?
    </div>
    <div data-bind="foreach: PreviousSurnames">
        <div>
            <input type="text" data-bind="value: $data">
            <span data-bind="click: $root.removePreviousSurname">Remove</span>
        </div> 
    </div>


var myViewModelExample = function () {
    var self = this;

    self.PreviousSurnames = ko.observableArray(['SURNAME1', 'SURNAME2', 'SURNAME3']);

    self.removePreviousSurname = function (surname) {
        self.PreviousSurnames.remove(surname);
    };

    self.PreviousSurnames_Click = function () {
        if (self.PreviousSurnames().length === 0) {
            self.PreviousSurnames.push('');
        }
        else {
            self.PreviousSurnames.removeAll();
        }
        alet(2)
    }

}

ko.applyBindings(new myViewModelExample());
like image 933
DavidReid Avatar asked Feb 25 '14 16:02

DavidReid


1 Answers

If you are using together the click and the checked then you need to return true from your click handler to allow the browser default click action which is in this case checking the checkbox:

self.PreviousSurnames_Click = function () {
    if (self.PreviousSurnames().length === 0) {
        self.PreviousSurnames.push('');
    }
    else {
        self.PreviousSurnames.removeAll();
    }
    return true;
}

Demo JSFiddle.

like image 182
nemesv Avatar answered Nov 15 '22 07:11

nemesv