2

I have a set of checkboxes, something like this:

<label class="checkbox-inline">
  <input type="checkbox" id="" value="1"> information
</label>
<label class="checkbox-inline">
  <input type="checkbox" id="" value="2"> information
</label>
<label class="checkbox-inline">
  <input type="checkbox" id="" value="3"> information
</label>        
<label class="checkbox-inline">
  <input type="checkbox" id="" value="4"> any
</label>

Using these checkboxes, users can make make selection. But if a user selects the "any" checkbox then I need to deselect all other selection.

I tried it something like this, but it doesn't work for me.

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

Can anybody tell me how can I do this in jquery?

NOTE: I am using dynamically generated HTML for my checkboxes.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
MCC
  • 47
  • 1
  • 6
  • 5
    Your functionality is better achieved with the proper type which is radio – mplungjan May 31 '15 at 09:57
  • 1
    Yes, use radio buttons if this is the behavior you need. You'll get away with no JS at all, better performance and without breaking the WYSIWYG model, because users EXPECT checkboxes to allow for multiple choices while radiobuttons only allow one choice. The UX (User Experience) will be much better! – pid May 31 '15 at 10:00
  • @mplungjan, I can not use radio for this. Because if user want to select many check boxes it should be done with this. That mean if user want it is possible to select 1st three checkboxes (see about html). But If user select 4th one "any" others should be unchecked.... Clear? – MCC May 31 '15 at 10:12
  • See my answer, its funny why most of us pointing out the wrong issue :) Including myself by the way :) – Anonymous Duck May 31 '15 at 10:23

4 Answers4

3

Define an id into the any checkbox, like this:

<label class="checkbox-inline">
  <input type="checkbox" id="" value="1"> information
</label>
<label class="checkbox-inline">
  <input type="checkbox" id="" value="2"> information
</label>
<label class="checkbox-inline">
  <input type="checkbox" id="" value="3"> information
</label>        
<label class="checkbox-inline">
  <input type="checkbox" id="any-checkbox" value="4"> any
</label>

I suggest this because it is not a good idea to use the fact that it is the fourth. If you add another checkbox in the future before it, then it will no longer be the fourth.

    //We use .on to tackle with the dynamic nature of the HTML
    $( "body" ).on( "change", ".checkbox-inline > input[type=checkbox]", function() {
        if ($(this).attr("id") === "any-checkbox") { //Any checkbox tick
            if ($(this).prop("checked")) { //User checked any
                //Other checkboxes are unchecked
                $(".checkbox-inline > input[type=checkbox]:not(#any-checkbox)").prop("checked", false)
            }
        } else { //Other checkbox tick
            if ($(this).prop("checked")) {//User checked another checkbox
                //Any checkbox is unchecked
                $("#any-checkbox").prop("checked", false);
            }
        }
    });

EDIT: As per the comment, I have solved the issue for multiple groups, like this:

<label class="checkbox-inline">
  <input type="checkbox" id="" name="hairColor" value="1"> information
</label>
<label class="checkbox-inline">
  <input type="checkbox" id="" name="hairColor" value="2"> information
</label>
<label class="checkbox-inline">
  <input type="checkbox" id="" name="hairColor" value="3"> information
</label>        
<label class="checkbox-inline">
  <input type="checkbox" id="hairColor" name="hairColor" value="4" class="any"> any
</label>
   <br> 
<label class="checkbox-inline">
  <input type="checkbox" id="" name="eyeColor" value="1"> eyeColor
</label>
<label class="checkbox-inline">
  <input type="checkbox" id="" name="eyeColor" value="2"> eyeColor
</label>
<label class="checkbox-inline">
  <input type="checkbox" id="" name="eyeColor" value="3"> eyeColor
</label>        
<label class="checkbox-inline">
  <input type="checkbox" id="eyeColor" name="eyeColor" class="any" value="4"> any
</label>

//We use .on to tackle with the dynamic nature of the HTML
$( "body" ).on( "change", ".checkbox-inline > input[type=checkbox]", function() {
    if ($(this).hasClass("any")) { //Any checkbox tick
        if ($(this).prop("checked")) { //User checked any
            //Other checkboxes are unchecked
            $(".checkbox-inline > input[type=checkbox][name=" + $(this).attr("name") + "]:not(.any)").prop("checked", false)
        }
    } else { //Other checkbox tick
        if ($(this).prop("checked")) {//User checked another checkbox
            //Any checkbox is unchecked
            $("[name=" + $(this).attr("name") + "].any").prop("checked", false);
        }
    }
});
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • @MCC, you are right, I had a typo, an id was not in quotes. Edited my answer. See this fiddle: http://jsfiddle.net/6D9kS/161/ – Lajos Arpad May 31 '15 at 14:30
  • One more question. How this code modify If I have checkboxes under different different grops. Check this fiddle - http://jsfiddle.net/6D9kS/163/ – MCC May 31 '15 at 15:57
  • I have changed a little bit of this and a little bit of that. The main idea was to show the groups as being part of classes and any is signed as a class as well, since it is no longer unique on the page. – Lajos Arpad May 31 '15 at 16:20
  • I am not sure it was adequate to unmark the answer, since it answered your initial question. However, I have solved the problem for you anyway. Here it is: http://jsfiddle.net/6D9kS/166/ – Lajos Arpad May 31 '15 at 16:25
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/79258/discussion-between-mcc-and-lajos-arpad). – MCC May 31 '15 at 16:30
  • Lajos Arpad, this final code is not working when change name attribute to array type. Like - `hairColor[]` what would be the issue? Thank you. – MCC Jun 01 '15 at 14:22
  • I am not sure, but I believe that you have a problem with the selector containing the name. This code occurs twice: [name=" + $(this).attr("name") + "] If you look at the value, then this is how it looks: [name=hairColor[]]. As you can see, the inner square brackets hinders the feature. You might need to escape it. You need a result, like [name=hairColor\[\]] where you escape the brackets with \. I would implement a function to tackle with this. – Lajos Arpad Jun 02 '15 at 07:04
  • Lajos Arpad, I am not sure how to build a function to fix this issue. Can you kindly guide me to implement it? Thank you my friend... – MCC Jun 02 '15 at 14:27
  • Surely. However, this answer is already long. I believe you should either ask a new question or ask me on a different channel. This answer would be too busy and escaping characters in selectors deserves to be talked about separately. – Lajos Arpad Jun 03 '15 at 09:29
  • Hi my friend, I asked this issue in separate question - this is the link to. http://stackoverflow.com/questions/30732056/how-i-disable-or-uncheck-all-checkboxes-if-one-checked-in-array When you have time give me a best solution for it. Thank you. – user3733831 Jun 09 '15 at 12:37
  • I like the accepted answer. I have added mine as well. – Lajos Arpad Jun 09 '15 at 13:14
2

Try this, it is fulfill your requirements

$(document).on("change", "input", function() {
  if ($("input[value=4]").is(":checked")) {
    $("input[value!=4]").attr("checked", false);

  }

});

$(document).ready(function() {
  for (i = 1; i < 4; i++) {
    $("#container").append("<label class='checkbox-inline'>  <input type='checkbox' id='' value='" + i + "'>information</label>")
  }
  $("#container").append("<label class='checkbox-inline'>  <input type='checkbox' id='' value='4'>any</label>");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div id="container"></div>
user786
  • 3,902
  • 4
  • 40
  • 72
1

Hi I edited my answer,

The funny part is, most of us is focusing on the click of the label but what were trying to capture is the click event of the checkbox @.@

I made this work by modfying ur code :

<label class="checkbox-inline">
  <input class ="checkbox1" type="checkbox" id="" value = "1" > information
</label>
<label class="checkbox-inline">
  <input class ="checkbox1" type="checkbox" id="" value = "2"> information
</label>
<label class="checkbox-inline">
  <input class ="checkbox1" type="checkbox" id="" value = "3"> information
</label>        
<label class="checkbox-inline">
  <input class ="checkbox1" type="checkbox" id="" value = "4"> any
</label>


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

I added separate class for the checkboxes and trap its click event. It works!! :P

EDIT : If "any" checkbox has a special logic,

$('.checkbox1').click(function(){
    if ($(this).val() != 4 && $("input[value=4]").is(":checked"))
        return false;
    // Check if any was checked
    if ($(this).val() == 4) 
      $("input[value!=4]").removeAttr('checked');
    //$(this).prop('checked', true);
})

Two scenarios trapped. 1. Unchecked other checkboxes if any checkbox was checked 2. Do not allow checking of other checkboxes if any was checked

P.S I reused some code from answer of @Alex :D

Anonymous Duck
  • 2,942
  • 1
  • 12
  • 35
1

You can use this jquery code where input_id will be id of your checkboxes.

$(document).on('click', "#input_id :checkbox", function() {
    if ($(this).is(':checked')) {
        $("#input_id :checkbox").prop('checked', false);
        $(this).prop('checked', true);
    }
})
Muhammad Irfan
  • 228
  • 1
  • 8