Home > Mobile >  Default radio button option with jquery
Default radio button option with jquery

Time:02-10

I am trying to hide/show different divs using the method shown checked but not showing

but I have to click it again to actually load the red div:

shows after clicking

Is there an elegant way to fix that so it is showing the red div when the page loads?

Thanks a lot, Alex

CodePudding user response:

How about just adding the $('.red').show() to set which box should be shown as default?

$(document).ready(function () {
  $('input[type="radio"]').click(function () {
    var inputValue = $(this).attr('value');
    var targetBox = $('.'   inputValue);
    $('.box').not(targetBox).hide();
    $(targetBox).show();
  });

  $('.red').show();
});
.box {
  color: #fff;
  padding: 20px;
  display: none;
  margin-top: 20px;
}
.red {
  background: #ff0000;
}
.green {
  background: #228b22;
}
.blue {
  background: #0000ff;
}
label {
  margin-right: 15px;
}
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<body>
    <div>
        <label><input type="radio" name="colorRadio" value="red" checked> red</label>
        <label><input type="radio" name="colorRadio" value="green"> green</label>
        <label><input type="radio" name="colorRadio" value="blue"> blue</label>
    </div>
    <div >You have selected <strong>red radio button</strong> so i am here</div>
    <div >You have selected <strong>green radio button</strong> so i am here</div>
    <div >You have selected <strong>blue radio button</strong> so i am here</div>
</body>

  • Related