Switch content after checking switch using jQuery

How can I fix the problem? I would like to switch the contents of each switch, if selected. Also, how can I set the default switch?

$(".option-detail").hide();
$(".option").click(function() {
  $(this).next('div').slideToggle(this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <ul>
    <li>
      <input type="radio" class="option">Option 1
      <div class="option-detail">Some content here</div>
    </li>
    <li>
      <input type="radio" class="option">Option 2
      <div class="option-detail">Some content here</div>
    </li>
    <li>
      <input type="radio" class="option">Option 3
      <div class="option-detail">Some content here</div>
    </li>
  </ul>
</div>
Run codeHide result
+4
source share
1 answer

Relevant Specifications - 17 Forms /17.2.1 Control Types

Radio buttons are similar to flags, except that when several use the same control name, they are mutually exclusive : when you switch "on", all others with the same name are disabled.

, , .

<input type="radio" name="group" class="option">
$(':input').on('change', function() {
  $(".option-detail").slideUp();
  $(this).parent('label').next('div').slideToggle(this.checked);
});

, :

  • input label, . , .
  • click change.
  • .option-detail . .

, , checked.

<input type="radio" name="group" class="option" checked>

<input type="radio" name="group" class="option" checked="checked">

$(".option-detail").hide();

$(':input').on('change', function() {
  $(".option-detail").slideUp();
  $(this).parent('label').next('div').slideToggle(this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <ul>
    <li>
      <label><input type="radio" name="group" class="option" checked>Option 1</label>
      <div class="option-detail">Some content here</div>
    </li>
    <li>
      <label><input type="radio" name="group" class="option">Option 2</label>
      <div class="option-detail">Some content here</div>
    </li>
    <li>
      <label><input type="radio" name="group" class="option">Option 3</label>
      <div class="option-detail">Some content here</div>
    </li>
  </ul>
</div>
Hide result
+2

All Articles