-1

I have the following code, to select the value of a select and when choosing to return the value to check the checkbox if it is true.

$('#title').change(function(){
  var data = {"title":$('#title').val()};
  $.ajax({
    type:"POST",
    url:"./atribvisit2",
    dataType:"Json",
    data:data,
    success:function(callback){
      var data_array = callback;
      artdat = data_array
      $("#certificad").html(artdat);
      document.getElementById('certificad').value = artdat;
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="form-group">
  <label for="title" class="col-sm-4 control-label">NOME UTENTE</label>
  <div class="col-sm-8">
    <select name="title" class="form-control" id="title">
      <option value=""></option>
        <?php
         $sql = "SELECT * FROM raddb.Utente WHERE ativo = '1' AND codigo NOT IN ('701', '723') ORDER BY nome ASC";
         $qr = mysqli_query($conn, $sql);
         while($ln = mysqli_fetch_assoc($qr)){
         echo '<option value="'.$ln['codigo'].'">'.$ln['nome'].'</option>';
         }
         ?>
    </select>
  </div>
</div>

<div class="switch-field">
  <input type="checkbox" id="certificad" name="certificad" value="1" />
  <label for="certificad">Com Certificado</label>
</div>

I intend that if the value returned is equal to 1, that the checkbox automatically checks. If it is different from 1, do not check the checkbox.

Can you help?

j08691
  • 204,283
  • 31
  • 260
  • 272
Bruno
  • 801
  • 5
  • 11
  • `.checked = true` is how you check a checkbox, not setting its value. – Barmar Mar 08 '22 at 18:11
  • Does this answer your question? [Setting "checked" for a checkbox with jQuery](https://stackoverflow.com/questions/426258/setting-checked-for-a-checkbox-with-jquery) – Don't Panic Mar 08 '22 at 22:20

1 Answers1

1

You can simply use checked prop of jquery html element

$('#title').change(function(){
      var data = {"title":$('#title').val()};
      $.ajax({
         type:"POST",
         url:"./atribvisit2",
         dataType:"Json",
         data:data,
         success:function(callback){
             var data_array = callback;
             artdat = data_array
             $("#certificad").html(artdat);
             $('#certificad').val(artdat);
             $('#certificad').prop('checked', artdat == '1');
        }
     });
});
Abhay Prince
  • 2,032
  • 1
  • 15
  • 17