javascriptjquerycheckboxprop

prop checked does not work - special case


Why when you click on the first button does not checked? Why when referring to the same checkbox one script does not work while the other does it correctly?

$('.button1').click(function(event) {
  //console.log("click1");
  $('#table1 .checkbox1').prop('checked',true);
});
$('.button2').click(function(event) {
  //console.log("click2");
  $('.checkbox1').prop('checked',true);
});
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<table id="table1">
  <input type="checkbox" class="checkbox1" />
  <input type="button" class="button1"  value="Checked1" />
  <input type="button" class="button2"  value="Checked2" />
</table>


Solution

  • Because the browser is cleaning your markup, and removing <table id="table1"></table> (because it's not valid markup for a complete markup -- input cannot be a direct child of table).

    As such, your selector (#table1 .checkbox1) does not match any elements. Your rendered markup looks like this:

    <input type="checkbox" class="checkbox1" />
    <input type="button" class="button1" value="Checked1" />
    <input type="button" class="button2" value="Checked2" />
    
    <table id="table1">
    
    </table>
    

    Image for reference from Chrome Dev Tools:

    enter image description here