开发者

jquery checkbox operation help needed

开发者 https://www.devze.com 2023-01-27 02:13 出处:网络
I don\'开发者_JAVA百科t how to do the coding in jquery for checkbox <p class=\"list\"> <label for=\"chkSunday\"><input type=\"checkbox\" checkedname=\"chkday\" id=\"chkday0\" value=\"0

I don'开发者_JAVA百科t how to do the coding in jquery for checkbox

<p class="list">
  <label for="chkSunday"><input type="checkbox" checked   name="chkday" id="chkday0" value="0" />All days</label>
  <label for="chkSunday"><input type="checkbox"  name="chkday" id="chkday1" value="1"  />Sunday</label>
  <label for="chkMonday"><input type="checkbox"  name="chkday" id="chkday2" value="2" />Monday</label>
  <label for="chkTuesday"><input type="checkbox"  name="chkday" id="chkday3" value="3" />Tuesday</label>
  <label for="chkWednesday"><input type="checkbox"  name="chkday" id="chkday4" value="4"  />Wednesday</label>
  <label for="chkThursday"><input type="checkbox"  name="chkday" id="chkday5" value="5" />Thursday</label>
  <label for="chkFriday"><input type="checkbox"  name="chkday" id="chkday6" value="6" />Friday</label>
  <label for="chkSaturday"><input type="checkbox"  name="chkday" id="chkday7" value="7"  />Saturday</label>
</p>

In above check boxes I have some use cases:

  • Usecase 1
    • User selected any of the day then "all" check box should uncheck
  • Use case 2
    • User unchecked all days then "all" check box should checked

I dont know how to handle this in jQuery.


I think this is what you're after:

$(".list :checkbox").change(function() {
  if(this.id == "chkday0") $(".list :checkbox:gt(0)").attr("checked", false);
  $("#chkday0").attr("checked", $(".list :checkbox:gt(0):checked").length == 0);
});

You can test it out here. What this is doing is rigging up a change handler to every checkbox in that <p>.

  • If it's the first (all), clear all the other days.
  • No matter which one it was, check the first if none others are selected (check All if no days).

Also note in the demo the <label> elements changed...they had invalid for attributes, and since they wrap the <input> they go with, you can just remove the for anyway.


This is pretty similar to @Nick's answer, but avoids some of the DOM selection. It assumes a static group of elements.

Example: http://jsfiddle.net/patrick_dw/7UwLU/

var $allBoxes = $('p.list input:checkbox').change(function() {
    var $dayBoxes = $allBoxes.slice(1);
    if ($allBoxes[0].checked) $dayBoxes.not(this).attr('checked', '');
    $allBoxes[0].checked = !$dayBoxes.filter(':checked').length;
});

No need to change the accepted answer. Just showing another way.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号