Set up a checkbox, analyzing an already checked checkbox. Jquery

0

I have the following situation:

I need to make clicking a Jquery button check if a checkbox on the page is set to true, and if so, make another checkbox also marked true

I tried to use the following code, but without success:

$("#button").click(function(){ 
      if ($('.box1').is(':checked')) {
          $(".box2").prop('checked', true);
      }
});

I tried to use the attr function, but it also did not work.

    
asked by anonymous 17.07.2017 / 02:25

1 answer

0

Looking at the code jQuery seems correct, but it failed to put html , the example below is an example of what your code would look like:

$("#button").click(function() {
  if ($('.box1').is(':checked')) {
    $(".box2").prop('checked', true);
  } else {
    $(".box2").prop('checked', false);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="checkbox" class="box1" />
<input type="checkbox" class="box2" />
<button type="button" id="button">Verificar</button>

I believe that the selector used is not ideal, because if your page contains more with this selector your code can cause problems and selects items that were not to be selected, the ideal way I understand would be with a name single in% w /% of each% w / w%

$("#button").click(function() {
  if ($('#box1').is(':checked')) {
    $("#box2").prop('checked', true);
  } else {
    $("#box2").prop('checked', false);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="checkbox" id="box1" />
<input type="checkbox" id="box2" />
<button type="button" id="button">Verificar</button>
    
17.07.2017 / 03:25