Make a select and checkbox to have a behavior similar to radio button

Asked

Viewed 863 times

4

Knockoutjs

I’m having a hard time getting values from input within a table to compare it would have to be like a radio button, but there are two checkbox as can be seen in down below:

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();
<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" />	
    <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>

Observing: am using then this table is generating dynamically where I can have several tables.

Basically I’m trying to do as if checkbox was like a radio button in a radio group

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>

Well my question is duplicate that"mark a checkbox and uncheck the others", however I use the code and see what happens, in my I have to mark all the check to work properly and still in my project that the fields is generated dynamically it peel all the checks that should not happen, however when you click on the check again it has to uncheck when it is marked.

1 answer

3


That’s what you need?

$(document).ready(function(){
  $(document).on('change', ':checkbox', function(){
    //Verifica se o checkbox clicado está checado
    if($(this).is(':checked')){
        //Desmarca os demais checkbox que estão na mesma tabela que o checkbox clicado
        $(this).closest('table').find(':checkbox').not(this).prop('checked', false);  
        //Atribui o valor 0 para o select que esteja na mesma tabela que o checkbox clicado
        $(this).closest('table').find('select').prop('value', 0);
    }
  });
  $(document).on('change', 'select', function(){
      //Desmarca os checkbox que estão na mesma tabela do select que teve um valor selecionado
      $(this).closest('table').find(':checkbox').prop('checked', false);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="tg" data-id="${$index}">

Tabela 1

 <tr>
  <td class="tg-yw4l"><span for="active">Comforme: </span></td>
 <td><input type="checkbox" value="1" data-bind="checkedValue:Comformity, checked: Comformity" /></td>
</tr>                   
<tr>
<td class="tg-yw4l"><span for="active">Oportunidade de Melhoria: </span></td>
<td><input type="checkbox" value="1" data-bind="checkedValue:OM, checked:OM" id="OM" /></td>
</tr>
<tr>
<td class="tg-yw4l" ><span>Não Conformidade: </span></td>
<td class="tg-yw4l">
<span>
<select data-bind="value: NonComformityType" id="NonComformityType">
<option value="0" selected>Escolher</option>
<option value="2">Maior</option>
<option value="1">Menor</option>
</select>
</span>
</td>
</tr>

 </table>

<br><br>

<table class="tg" data-id="${$index}">

Tabela 2

 <tr>
  <td class="tg-yw4l"><span for="active">Comforme: </span></td>
 <td><input type="checkbox" value="1" data-bind="checkedValue:Comformity, checked: Comformity" /></td>
</tr>                   
<tr>
<td class="tg-yw4l"><span for="active">Oportunidade de Melhoria: </span></td>
<td><input type="checkbox" value="1" data-bind="checkedValue:OM, checked:OM" id="OM" /></td>
</tr>
<tr>
<td class="tg-yw4l" ><span>Não Conformidade: </span></td>
<td class="tg-yw4l">
<span>
<select data-bind="value: NonComformityType" id="NonComformityType">
<option value="0" selected>Escolher</option>
<option value="2">Maior</option>
<option value="1">Menor</option>
</select>
</span>
</td>
</tr>

 </table>
 
<br><br>

<table class="tg" data-id="${$index}">

Tabela 3

 <tr>
  <td class="tg-yw4l"><span for="active">Comforme: </span></td>
 <td><input type="checkbox" value="1" data-bind="checkedValue:Comformity, checked: Comformity" /></td>
</tr>                   
<tr>
<td class="tg-yw4l"><span for="active">Oportunidade de Melhoria: </span></td>
<td><input type="checkbox" value="1" data-bind="checkedValue:OM, checked:OM" id="OM" /></td>
</tr>
<tr>
<td class="tg-yw4l" ><span>Não Conformidade: </span></td>
<td class="tg-yw4l">
<span>
<select data-bind="value: NonComformityType" id="NonComformityType">
<option value="0" selected>Escolher</option>
<option value="2">Maior</option>
<option value="1">Menor</option>
</select>
</span>
</td>
</tr>

 </table>

  • @Brunoh. I edited the answer by putting two different tables and modifying the script a little, now it’s not interfering with us inputs from the other table.

  • @Brunoh. I believe that now does not interfere more in the inputs of other tables, I did the example by putting 3 equal tables and only changes the inputs of the table corresponding to checkbox or select clicked.

Browser other questions tagged

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