Check only one checkbox and unchek others

DELION picture DELION · Apr 16, 2015 · Viewed 14.3k times · Source

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.

Answer

kapantzak picture kapantzak · Apr 16, 2015

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" />