0

I have 3 checkbox, for which I want only 1 checkbox to be checked at a time. below is my fiddle for the html

JS fiddle

I want this to be worked in IE8 also kindly suggest how to do

Nad
  • 4,605
  • 11
  • 71
  • 160
  • 4
    _"I want only 1 checkbox to be checked at a time"_, if you want that then why not use radio buttons which have that functionality built in – Patrick Evans May 03 '16 at 11:17
  • @PatrickEvans: I know it has inbuilt functionality of that,. But the client requirements is on the basis of `checkbox` :( – Nad May 03 '16 at 11:19
  • You can take a look at this post: http://stackoverflow.com/questions/15548041/how-to-make-a-checkbox-list-behave-like-radio-button-in-vb-net. – ConnorsFan May 03 '16 at 11:55
  • @ConnorsFan: same issue, not working. I am able to check all the checkboxes – Nad May 03 '16 at 12:10

2 Answers2

11

How about this - fiddle:

<input type="checkbox" class="chk" />
<input type="checkbox" class="chk" />
<input type="checkbox" class="chk" />
<input type="checkbox" class="chk" />

$('input.chk').on('change', function() {
    $('input.chk').not(this).prop('checked', false);  
});

Edit: for second part of your question to un-check other checkboxes when selecting parent checkbox see this fiddle - (as per chat) :

if (!cb.checked) { 
$('#trchkOptions input[type=checkbox]').attr('checked', false); 
}
Zaki
  • 5,540
  • 7
  • 54
  • 91
  • You need Jquery included also make sure your checkboxes are not asp.net as it will change the ID, if it is set it to static. see fiddle, if pure Javascript then see Gokul's answer – Zaki May 03 '16 at 11:28
  • if you click on it will tell you where the error is you must have included something like extra > – Zaki May 03 '16 at 11:36
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/110902/discussion-between-coder-and-zaki). – Nad May 03 '16 at 11:39
  • hi check chat room – Zaki May 04 '16 at 08:23
  • Thanku so much Zaki.!! – Nad May 04 '16 at 10:38
2

function selectOnlyThis(id) {
    for (var i = 1;i <= 4; i++)
    {
        document.getElementById(i).checked = false;
    }
    document.getElementById(id).checked = true;
}
<input type="checkbox" id="1" value="Value1" onclick="selectOnlyThis(this.id)" /> Option 1
<input type="checkbox" id="2" value="Value1" onclick="selectOnlyThis(this.id)" /> Option 2
<input type="checkbox" id="3" value="Value1" onclick="selectOnlyThis(this.id)" /> Option 3
<input type="checkbox" id="4" value="Value1" onclick="selectOnlyThis(this.id)" /> Option 4

It should help you

Gokul Shinde
  • 957
  • 3
  • 10
  • 30
  • I get error as `Microsoft JScript runtime error: 'document.getElementById(...)' is null or not an object` – Nad May 03 '16 at 12:38