'Default radio button option with jquery
I am trying to hide/show different divs using the method shown here.
<style>
.box{
color: #fff;
padding: 20px;
display: none;
margin-top: 20px;
}
.red{ background: #ff0000; }
.green{ background: #228B22; }
.blue{ background: #0000ff; }
label{ margin-right: 15px; }
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$('input[type="radio"]').click(function(){
var inputValue = $(this).attr("value");
var targetBox = $("." + inputValue);
$(".box").not(targetBox).hide();
$(targetBox).show();
});
});
</script>
</head>
<body>
<div>
<label><input type="radio" name="colorRadio" value="red" checked = "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 class="red box">You have selected <strong>red radio button</strong> so i am here</div>
<div class="green box">You have selected <strong>green radio button</strong> so i am here</div>
<div class="blue box">You have selected <strong>blue radio button</strong> so i am here</div>
</body>
I would like to have the red button clicked by default when the page loads. However if I just change the label to this:
<label><input type="radio" name="colorRadio" value="red" checked = "checked"> red</label>
It shows as clicked:
but I have to click it again to actually load the red div:
Is there an elegant way to fix that so it is showing the red div when the page loads?
Thanks a lot, Alex
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
