lundi 18 février 2019

If checkbox is already checked on load

Using this jquery, i'm looping through elements and checking whether the relevant checkbox is checked.

When the page loads, the checkboxes are checked, but the console is showing console.log( id + ' not checked' );

Have I missed something, because as far as I can see it should be showing console.log( id + ' checked' ); in the console

Code and HTML:

$(document).ready(function(e) {
  $('.row').each(function(index, element) {
    console.log($(element).attr("id"));
    default_status($(element).attr("id"));
  });
});

function default_status(id) {
  if ($('#dr_default_' + id).is(':checked')) {
    console.log(id + ' checked');
    for (i = 1; i < 4; i++) {
      $('#dr_number' + i + '_' + id).val('');
      $('#dr_number' + i + '_' + id).attr('placeholder', 'default');
      $('#dr_number' + i + '_' + id).attr('disabled', true);
      $('#dr_number' + i + '_' + id).removeClass('required');
    }
  } else {
    console.log(id + ' not checked');
    for (i = 1; i < 4; i++) {
      $('#dr_number' + i + '_' + id).val('');
      $('#dr_number' + i + '_' + id).attr('placeholder', '');
      $('#dr_number' + i + '_' + id).attr('disabled', false);
      $('#dr_number' + i + '_' + id).addClass('required');
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td><input type="checkbox"></td>
    <td><input type="checkbox" id="dr_default_1" class="row" onclick="default_status('1');" checked="checked"></td>
    <td>1</td>
    <td></td>
    <td><input type="text" name="" id="dr_number1_1" class="form-control" /></td>
    <td><input type="text" name="" id="dr_number2_1" class="form-control" /></td>
    <td><input type="text" name="" id="dr_number3_1" class="form-control" /></td>
    <td>
      <select name="" id="dr_dialing_1" class="form-control">

      </select>
    </td>
  </tr>

  <tr>
    <td><input type="checkbox"></td>
    <td><input type="checkbox" id="dr_default_2" class="row" onclick="default_status('2');" checked="checked"></td>
    <td>2</td>
    <td></td>
    <td><input type="text" name="" id="dr_number1_2" class="form-control" /></td>
    <td><input type="text" name="" id="dr_number2_2" class="form-control" /></td>
    <td><input type="text" name="" id="dr_number3_2" class="form-control" /></td>
    <td>
      <select name="" id="dr_dialing_2" class="form-control">

      </select>
    </td>
  </tr>
</table>



Aucun commentaire:

Enregistrer un commentaire