Home  >  Q&A  >  body text

javascript - checkbox condition

<input id="a1" type="checkbox">
<label for="a1">1</label>
<input id="a2" type="checkbox">
<label for="a2">2</label>
<input id="a3" type="checkbox">
<label for="a3">3</label>
<input id="a4" type="checkbox">
<label for="a4">4</label>
<input id="a5" type="checkbox">
<label for="a5">5</label>

<script>
$(function()
{
  disabledOtherBox();
  $("#a1").click(disabledOtherBox);
  disabledA1Box();
  $("#a2,#a3,#a4,#5").click(disabledA1Box);
});

function disabledOtherBox()
{
  if (this.checked)
  {
    $("#a2,#a3,#a4,#a5").attr("disabled", true);
  }
  else
  {
    $("#a2,#a3,#a4,#a5").removeAttr("disabled");
  }
}

function disabledA1Box()
{
  if (this.checked)
  {
    $("#a1").attr("disabled", true);
  }
  else
  {
    $("#a1").removeAttr("disabled");
  }
}
</script>

The above are the conditions I wrote
If a1 is checked
a2~5 is locked

If one of a2~a5 is checked
, then a1 is locked

I want to add another condition but I still can’t figure it out
That is, assuming that one of a2~5 is checked (or two, three, or four are all checked)
Then a1 Just lock it
Unless a2~5 are not checked
, a1 will be opened

習慣沉默習慣沉默2734 days ago634

reply all(1)I'll reply

  • 習慣沉默

    習慣沉默2017-05-19 10:49:09

    <script>
        $(function(){
            var a1 = $("#a1");
            var other = $("#a2,#a3,#a4,#a5");
            
            a1.click(function(){
                disabledBox(other,this.checked)
            });
            
            other.click(function() {
                  var r = false;
                
                other.each(function() {
                    if(this.checked) {
                        r = true;
                        return false;
                      }
                })
                  
                  disabledBox(a1,r)
            });
           
            //如a1已勾选,则#a2,#a3,#a4,#5锁住
            //disabledBox(other,a1.attr('checked'))
            
            //如#a2,#a3,#a4,#5其中一个或多个已勾选,则a1锁住
            other.each(function() {
                 if(this.checked) {
                    disabledBox(a1,true)
                     return false;
                 }
            })
        });
        
        function disabledBox(el,disabled){
            el.attr("disabled", !!disabled);
        }
    </script>

    reply
    0
  • Cancelreply