Skip to content Skip to sidebar Skip to footer

How To Clear Table Data If It's Hide

I have some tables which will show depending on radio button. If radio button value is 'YES' then show the table if 'No' then hide. I got the solution how to do that. Now I want to

Solution 1:

If you mean by clearing out the table to remove all rows, then you can use table.html(''); where table is assigned $(this).closest('.form-group').next('table'). If you mean to just clear out the input fields, the easiest way to do that is to enclose your fields in a <form> and to do a form reset.

See (and run) the code snippet below:

$(document).ready(function() {
  $('.form-check-inline input[type="radio"]').on('change', function() {
    let table = $(this).closest('.form-group').next('table');
    if (this.value === 'No') {
      $('#f').trigger('reset');
      table.hide();
    }
    else {
      table.show();
    }
  });
});
.show-dc-table {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="f">
<div class="form-group row">
  <label class="col-sm-2 col-form-label">Do you have allergies?</label>
  <div class="col-sm-10">
    <div class="form-check form-check-inline">
      <input class="form-check-input" type="radio" name="allergy" value="Yes">
      <label class="form-check-label">Yes</label>
    </div>
    <div class="form-check form-check-inline">
      <input class="form-check-input" type="radio" name="allergy" value="No">
      <label class="form-check-label">No</label>
    </div>
  </div>
</div>
<table class="table table-striped show-dc-table">
  <thead>
    <tr>
      <th scope="col">Alergic Reactions to</th>
      <th scope="col">Yes</th>
      <th scope="col">No</th>
      <th scope="col">Notes</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Aspirin, Ibuprofen, Codeine</td>
      <td><input type="radio" name="a1" /></td>
      <td><input type="radio" name="a2" /></td>
      <td><input type="text" /></td>
    </tr>
  </tbody>
</table>
</form>

Post a Comment for "How To Clear Table Data If It's Hide"