最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to uncheck all checkboxes, if one checkbox checked? - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question edited May 31, 2015 at 10:17 mplungjan 178k28 gold badges182 silver badges240 bronze badges asked May 31, 2015 at 9:55 MCCMCC 471 silver badge6 bronze badges 4
  • 5 Your functionality is better achieved with the proper type which is radio – mplungjan Commented May 31, 2015 at 9: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 Commented May 31, 2015 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 Commented May 31, 2015 at 10:12
  • See my answer, its funny why most of us pointing out the wrong issue :) Including myself by the way :) – Anonymous Duck Commented May 31, 2015 at 10:23
Add a ment  | 

4 Answers 4

Reset to default 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 ment, 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);
        }
    }
});

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./ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div id="container"></div>

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);
    }
})

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

发布评论

评论列表(0)

  1. 暂无评论