0

How to use javascript to checked and unchecked with function onclick like this ?

http://jsfiddle.net/A4wxX/98/

First, When you checked checkbox id="yyy" , checkbox id="yyy" wil Checked and checkbox id="xxx" wil Unchecked

And then, When you checked checkbox id="xxx" ,checkbox id="xxx" wil Checked checkbox id="yyy" wil Unchecked

on my code i must to double checked on checkbox for do that, how can i apply my code for single click ?

<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.js"></script>

<script type="text/javascript">
function SetCard() {
    var xxx_val = document.getElementById('xxx').checked 
    var yyy_val = document.getElementById('yyy').checked
    if(xxx_val === true)
    {
        document.getElementById('yyy').checked = false; 
    }
    if(yyy_val === true)
    {
        document.getElementById('xxx').checked = false;        
    }      
}    
</script>

<input type="checkbox" id="xxx" onclick="SetCard()" checked> xxx
<br>
<input type="checkbox" id="yyy" onclick="SetCard()"> yyy
  • http://stackoverflow.com/questions/5839884/make-checkbox-behave-like-radio-buttons-with-javascript answer here will help you – Lekhnath Dec 05 '14 at 07:11
  • 1
    It seems like you are looking for the functionality of a radiobutton http://www.w3schools.com/HTML/tryit.asp?filename=tryhtml_radio – Brian Ogden Dec 05 '14 at 07:11
  • 1
    If you have two options only and you need to give one option to check then use radio button instead of check-box Use following link to customize your radio button http://fronteed.com/iCheck/ – nikita Dec 05 '14 at 07:24

2 Answers2

0

HTML

<input type="checkbox" id="xxx" onclick="SetCard(event)" checked> xxx
<br>
<input type="checkbox" id="yyy" onclick="SetCard(event)"> yyy   

JS

function SetCard(e) {
    if (e && e.target) {
        if (e.target.id === 'xxx') {
            document.getElementById('yyy').checked = false;
        }
        else if (e.target.id === 'yyy') {
            document.getElementById('xxx').checked = false;
        }
    }

Fiddle: http://jsfiddle.net/95pnsq3q/

ryanlutgen
  • 2,951
  • 1
  • 21
  • 31
0

JS :

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

})

HTML :

<input type="checkbox" id="xxx" class="checkbox"  checked> xxx
<br>
<input type="checkbox" id="yyy" class="checkbox"> yyy  
Pankaj
  • 571
  • 5
  • 20