Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I disable all my unchecked boxes on pageload?

Tags:

jquery

When my page is loaded I wish all my unchecked boxes to be disabled:

<form action="demo_form.asp" method="get">
  <input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
  <input type="checkbox" name="vehicle" value="Car" checked> I have a car<br>
  <input type="submit" value="Submit">
</form>

I tried it with this code, but it is not working:

  $(document).ready(function(){
        if($(".test").is(':checked'))
            $(".test").attr("disabled", false);
        else
            $(".test").attr("disabled", true);
    });

https://jsfiddle.net/m7ny2Le7/1/

like image 642
peace_love Avatar asked Dec 15 '22 12:12

peace_love


1 Answers

You can use :not(:checked) to filter unchecked checkboxes

$(document).ready(function() {
  $(":checkbox:not(:checked)").prop('disabled', true)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="demo_form.asp" method="get">
  <input type="checkbox" name="vehicle" value="Bike">I have a bike
  <br>
  <input type="checkbox" name="vehicle" value="Car" checked>I have a car
  <br>
  <input type="submit" value="Submit">
</form>

Also you can use prop() with callback

$(document).ready(function() {
  $(":checkbox").prop('disabled', function() {
    return !this.checked;
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="demo_form.asp" method="get">
  <input type="checkbox" name="vehicle" value="Bike">I have a bike
  <br>
  <input type="checkbox" name="vehicle" value="Car" checked>I have a car
  <br>
  <input type="submit" value="Submit">
</form>

NOTE : In your code I can't see test class , so I'm using :checkbox to refer all checkbox.

like image 151
Pranav C Balan Avatar answered Jan 31 '23 00:01

Pranav C Balan