Coda Chang Coda Chang - 19 days ago 10
CSS Question

jQuery display dynamic div by choosing different checkbox

I want to display contact information by choosing different

checkbox
, like this picture:

enter image description here

Here is my code:



$(document).ready(function() {
$('input[type="checkbox"]').on('change', function() {
$('input[name="' + this.name + '"]').not(this).prop('checked', false);
$(this).closest('div').css("display", "block");
});
});

.receipt_info{
display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table">
<tbody>
<tr>
<td>
<input type="checkbox" name="receipt[]"/>
</td>
<td>Option1
<div class="receipt_info">
<div>
<label>name1</label>
</div>
<div>
<label>phone1</label>
</div>
<div>
<label>address1</label>
</div>
</div>
</td>
</tr>

<tr>
<td>
<input type="checkbox" name="receipt[]"/>
</td>
<td>Option2
<div class="receipt_info">
<div>
<label>name2</label>
</div>
<div>
<label>phone2</label>
</div>
<div>
<label>address2</label>
</div>
</div>
</td>
</tr>
</tbody>
</table>





I think I'm selecting wrong
div
, but I don't know how to fix it.

Answer

Use $(this).closest('tr').find('div.receipt_info') selector!

  • this refers to element on which event is invoked.
  • jQuery.closest will traverse up in DOMTree and returned matched element.
  • jQuery.find will find all the child of he current element.

$(document).ready(function() {
  $('input[type="checkbox"]').on('change', function() {
    $('input[name="' + this.name + '"]').not(this).prop('checked', false);
    $('.receipt_info').hide();
    $(this).closest('tr').find('div.receipt_info').show();
  });
});
.receipt_info {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table">
  <tbody>
    <tr>
      <td>
        <input type="checkbox" name="receipt[]" />
      </td>
      <td>Option1
        <div class="receipt_info">
          <div>
            <label>name1</label>
          </div>
          <div>
            <label>phone1</label>
          </div>
          <div>
            <label>address1</label>
          </div>
        </div>
      </td>
    </tr>

    <tr>
      <td>
        <input type="checkbox" name="receipt[]" />
      </td>
      <td>Option2
        <div class="receipt_info">
          <div>
            <label>name2</label>
          </div>
          <div>
            <label>phone2</label>
          </div>
          <div>
            <label>address2</label>
          </div>
        </div>
      </td>
    </tr>
  </tbody>
</table>