marcel marcel - 1 month ago 17
HTML Question

jquery disable checkbox by default

My current script is toggling between disabled and enabled.

<script>
$("#filter").attr('checked', !$("#mylist")[0].disabled);
$("#filter").click(function() {
$("#mylist").attr('disabled', !this.checked)
});
</script>


and my html code is:

<div>
<div class="checkbox">
<input type="checkbox" checked="checked" id="filter" />
<label for="filter">Types</label>
<br>
</div>
<select class="selectpicker" id="mylist" multiple>
<option>A</option>
<option>B</option>
<option>C</option>
</select>
</div>


by default the checkbox is checked, and when I remove the `checked="checked" , it doesn't work at all.

How can I disable this by default and only enable/disable it afterwards?

Answer

Are you need like this .If uncheck = disable ,check=enable.In default case is unchecked is disable.change with default checked its also enable

$(document).ready(function (){
$("#filter").attr('checked', false);
 if(!$("#filter").attr('checked')){ $("#mylist").attr('disabled',"true")}
$("#filter").click(function() {
  $("#mylist").attr('disabled', !this.checked)
});
  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div class="checkbox">
    <input type="checkbox"  id="filter" />
    <label for="filter">Types</label>
    <br>
  </div>
  <select class="selectpicker" id="mylist" multiple>
    <option>A</option>
    <option>B</option>
    <option>C</option>
  </select>
</div>