With knockoutjs make a Checkbox with Radiobutton behavior

Asked

Viewed 48 times

1

Well I already asked a question I tried all the code that was passing me and nothing, and it was marked as duplicate, However as can be seen in the code below does not work as desired.

function DemoItem(id, name) {
    var self = this;

    self.id = ko.observable(id);
    self.Name = ko.observable(name);
    self.Selected = ko.observable(false);
}

function ViewModel() {
    var self = this;

    self.availableItems = ko.observableArray();
    self.associatedItemIds = ko.observableArray();

    self.init = function () {
        self.availableItems.push(new DemoItem(1, 'One'));
        self.availableItems.push(new DemoItem(2, 'Two'));
        self.availableItems.push(new DemoItem(3, 'Three'));
        self.availableItems.push(new DemoItem(4, 'Four'));
        self.availableItems.push(new DemoItem(5, 'Five'));
    };
    
    self.toggleAssociation = function (item) {
        if (item.Selected() === true) console.log("dissociate item " + item.id());
        else console.log("associate item " + item.id());
        item.Selected(!(item.Selected()));
        return true;
    };
}

var viewModel = new ViewModel();
ko.applyBindings(viewModel);
viewModel.init();

function marcaDesmarca(caller) {
  var checks = document.querySelectorAll('input[type="checkbox"]');    
  for(let i = 0; i < checks.length; i++) {
    checks[i].checked = checks[i] == caller;   
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
Available Items:
<table data-bind="foreach: $root.availableItems">
    <tr><td><input type="checkbox" data-bind="value: id(), checked: $root.associatedItemIds, click: $root.toggleAssociation"  onclick="marcaDesmarca(this)"/>	
    <span data-bind="text: '&nbsp;' + Name()"></span>
    </td></tr>
</table>
<br/>
Associated Item Ids:
<div data-bind="foreach: $root.associatedItemIds">
        <span data-bind="text: $data"></span>
    <br/>
</div>

In my code I’m trying this way but you’re still in error:

ko.bindingHandlers.isSelected = {
                init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
                    $(element).checked = false;

                },
                update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
                    if ($(element).is(':checked')) {
                        //Desmarca os demais checkbox que estão na mesma tabela que o checkbox clicado
                        $(element).closest('table').find(':checkbox').not(element).prop('checked', false);
                        //Atribui o valor 0 para o select que esteja na mesma tabela que o checkbox clicado
                        $(element).closest('table').find('select').prop('value', 0);
                    }
                }
            };
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.