3

When I check the checkbox for 'Monday', the 'Tuesday' checked status is updated. It works well simultaneously.

But, once I click to check or uncheck 'Tuesday', and if I then check 'Monday', the 'Tuesday' doesn't change status as same as 'Monday' anymore. After checking/unchecking 'Tuesday' it doesn't sync with the 'Monday' checkbox.

$(function() {
  // main product upload
  $("#monday").change(function(e) {
    $("#tuesday").attr("checked", this.checked);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input type="checkbox" id="monday" name="monday">
<input type="checkbox" id="tuesday" name="tuesday">
connexo
  • 53,704
  • 14
  • 91
  • 128

4 Answers4

4

Use prop instead of attr.

$(function () {
    // main product upload
    $( "#monday" ).change(function(e) {
        $( "#tuesday" ).prop("checked", this.checked);
    });       
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>    

Monday: <input type="checkbox" id="monday" name="monday" > <br/>
Tues: <input type="checkbox" id="tuesday" name="tuesday" >
haldo
  • 14,512
  • 5
  • 46
  • 52
1

Another example of jQuery being a useless tool in most cases in 2021.

This is so easy to achieve without the use of any third-party code:

document.addEventListener('DOMContentLoaded', function() {
  document.getElementById('monday').addEventListener('change', function(e) {
    document.getElementById('tuesday').checked = e.target.checked;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input type="checkbox" id="monday" name="monday">
<input type="checkbox" id="tuesday" name="tuesday">
connexo
  • 53,704
  • 14
  • 91
  • 128
0

read this issue

the link is a issue thats explain the diference between prop and attr.

Properties are generally simpler to deal with than attributes. An attribute value may only be a string where as a property can be of any type. For example, the checked property is a Boolean. If you inspect your previus code you will see the code adding a string checked, but with prop its diferent.

Isac X
  • 1
  • 2
0

Answer for Interview :)

Both method are used for set and get value, 
attr() returns the default value (Original state) of a property
whereas prop() returns the current value (Current state).
nano dev
  • 335
  • 4
  • 6