仅当选中两个单选按钮并单击提交按钮时,我才需要显示文本。
我尝试了很多不同的方法来实现这一点,但没有任何效果。 我还想提一下,我对学习 JavaScript 还很陌生,所以有一个地方可以让我学习如何做到这一点,请告诉我。
这是我根据您的需求修改的基本代码片段 - 也许这会有所帮助:
<!DOCTYPE html>
<html>
<body>
<h1>Display Radio Buttons</h1>
<form action="/action_page.php">
<p>Please select your favorite Web language:</p>
<input type="radio" id="html" name="fav_language" value="HTML" checked>
<label for="html">HTML</label><br>
<input type="radio" id="css" name="fav_language" value="CSS">
<label for="css">CSS</label><br>
<input type="radio" id="javascript" name="fav_language" value="JavaScript">
<label for="javascript">JavaScript</label>
<br>
<p>Please select your age:</p>
<input type="radio" id="age1" name="age" value="30">
<label for="age1">0 - 30</label><br>
<input type="radio" id="age2" name="age" value="60" checked>
<label for="age2">31 - 60</label><br>
<input type="radio" id="age3" name="age" value="100">
<label for="age3">61 - 100</label><br><br>
<input type="button" value="Submit" id='btnSubmit'>
</form>
<p style="display: none" id="messageToShow">Hey im hidden</p>
<script>
window.onload = (event) => {
let btnRef = document.getElementById('btnSubmit');
let messageToShowRef = document.getElementById('messageToShow');
btnRef.addEventListener("click", () => {
let selectedAge = document.querySelector('input[name="age"]:checked').value;
let selectedFavLanguage = document.querySelector('input[name="fav_language"]:checked').value;
messageToShowRef.style.display = "block";
messageToShowRef.innerHTML = `>> hey world, clicked! Age:, ${selectedAge}, Fav Language:, ${selectedFavLanguage}`;
});
};
</script>
</body>
</html>
原始来源:https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_radio