Home > database >  Put checkbox checked if the returned value is true
Put checkbox checked if the returned value is true

Time:03-09

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 >
  <label for="title" >NOME UTENTE</label>
  <div >
    <select name="title"  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 >
  <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?

CodePudding user response:

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');
        }
     });
});
  • Related