Set a checkbox, analyzing an already marked checkbox. Jquery

Asked

Viewed 504 times

0

I have the following situation:

I need to make sure that by clicking a Jquery button, it analyzes whether a page checkbox is set to true, and if so, make another checkbox also marked as true;

I tried to use the following code, but to no avail:

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

I tried to use the attr function, but it didn’t work either.

  • The code works. There must be something else preventing it from working properly. Check that Jquery is loaded and is running only after the paging is loaded with $(function(){ ...

  • Has the html code?

  • Is this #button already on the page when jQuery is read? There is only one button with this ID and 1 checkbox for each class?

1 answer

0

Seeing the code jQuery seems correct, but, faltou put the html, The example below is an example of what it would be like to interface to your code:

$("#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>
<input type="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 ends up selecting items that were not to be selected, the ideal way to my understanding would be with a unique name on id of each checkbox

$("#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>
<input type="checkbox" id="box1" />
<input type="checkbox" id="box2" />
<button type="button" id="button">Verificar</button>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.