Estoy tratando de ocultar/mostrar diferentes divs usando el método que se muestra aquí .
<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>Me gustaría que se haga clic en el botón rojo de forma predeterminada cuando se carga la página. Sin embargo, si solo cambio la etiqueta a esto:
<label><input type="radio" name="colorRadio" value="red" checked = "checked"> red</label> Se muestra como se hace clic:

pero tengo que volver a hacer clic en él para cargar realmente el div rojo:

¿Hay alguna manera elegante de arreglar eso para que muestre el div rojo cuando se carga la página?
muchas gracias, alex
¿Qué tal simplemente agregar $('.red').show() para establecer qué cuadro debe mostrarse como predeterminado?
$(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 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>