Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check only one checkbox and unchek others

Im trying to check only one checkbox at the time and others uncheck , but when i want to check new chekcbox then pervious will uncheck and so on.

i tried this code:

JS file

$('input[type="checkbox"]').click(function() {
$(".check_class").attr("checked", false);
$(this).attr("checked", true);    
});

HTML file

    <ons-list-header>Takistused</ons-list-header>
    <ons-list-item modifier="tappable">
      <label class="checkbox checkbox--noborder checkbox--list-item">
        <input type="checkbox" id="example">
        <div class="checkbox__checkmark checkbox--noborder__checkmark checkbox--list-item__checkmark"></div>
        vihmaveerenn
      </label>
    </ons-list-item>
    <ons-list-item modifier="tappable">
      <label class="checkbox checkbox--noborder checkbox--list-item" id="test">
        <input type="checkbox" id="example">
        <div class="checkbox__checkmark checkbox--noborder__checkmark checkbox--list-item__checkmark" ></div>
        äärekivi
      </label>
    </ons-list-item>
    <ons-list-item modifier="tappable" >
      <label class="checkbox checkbox--noborder checkbox--list-item" id="test1">
        <input type="checkbox" id="example">
        <div class="checkbox__checkmark checkbox--noborder__checkmark checkbox--list-item__checkmark"></div>
        munakivi tee
      </label>
    </ons-list-item>
  </ons-list>

What im doing wrong? i have tried different approaches, but it just wont work in live use.

like image 389
DELION Avatar asked Apr 16 '15 13:04

DELION


Video Answer


2 Answers

Try the .not(this) like bellow:

$(document).on('click', 'input[type="checkbox"]', function() {      
    $('input[type="checkbox"]').not(this).prop('checked', false);      
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" id="one" />
<input type="checkbox" id="two" />
<input type="checkbox" id="three" />
<input type="checkbox" id="four" />
like image 85
kapantzak Avatar answered Sep 21 '22 21:09

kapantzak


You should really use radio buttons for this type of functionality, however you can simply exclude an item from a set of matches with not like this:

$('input[type="checkbox"]').click(function() {
   $('input[type="checkbox"]').not(this).prop("checked", false);
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/4n2e31oq/

Note you need to use prop and not attr for certain properties like checked.

You can make this a little more efficient by caching the selection of checkboxes:

var $checks = $('input[type="checkbox"]');
$checks.click(function() {
   $checks.not(this).prop("checked", false);
});

http://jsfiddle.net/TrueBlueAussie/4n2e31oq/1/

like image 32
Gone Coding Avatar answered Sep 22 '22 21:09

Gone Coding