我正在努力寻找一种方法来基于表单中的两个选项显示信息。我的意思是,“选择性别”中有两个选项。如果他们选择“男性”,则应出现一个段落。如果他们选择“女性”,则网站上将出现另一段。我该怎么办?
这是表格代码:
<form>
Select Gender
<br />
<input type="radio" name="gender" id="male">
<label for="male">Male</label>
<br />
<input type="radio" name="gender" id="female">
<label for="female">Female</label>
<br />
<br />
</form>
请注意,我在您的输入和div
周围添加了.popup-description
,否则将无法正常工作。
.popup-description{
display: none;
}
[type="radio"]:checked ~ label ~ .popup-description{
display: block;
}
<form>
Select Gender
<div>
<input type="radio" name="gender" id="male">
<label for="male">Male</label>
<p class="popup-description">
This text is shown when the user selects <b>male</b>.
</p>
</div>
<div>
<input type="radio" name="gender" id="female">
<label for="female">Female</label>
<p class="popup-description">
This text is shown when the user selects <b>female</b>.
</p>
</div>
</form>
请注意,我在您的value
中添加了input
,否则将无法正常工作。
$(document).ready(function(){
$("[name='gender']").on("change", function(){
var v = $(this).val();
var n = $(this).attr("name");
$(".popup-description[data-for='" + n + "']").hide();
$(".popup-description[data-for='" + n + "'][data-selected-value='" + v + "']").show();
});
});
.popup-description{
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
Select Gender
<br />
<input type="radio" name="gender" id="male" value="male">
<label for="male">Male</label>
<p class="popup-description" data-for="gender" data-selected-value="male">
This text is shown when the user selects <b>male</b>.
</p>
<br />
<input type="radio" name="gender" id="female" value="female">
<label for="female">Female</label>
<p class="popup-description" data-for="gender" data-selected-value="female">
This text is shown when the user selects <b>female</b>.
</p>
<br />
</form>
请注意,我在您的value
中添加了input
,否则将无法正常工作。
(function(){
var radios = document.querySelectorAll("[name='gender']");
if(radios !== null){
for(var i = 0; i < radios.length; i++){
var el = radios.item(i);
el.addEventListener("change", function(){
if(this.checked){
var v = this.value;
var n = this.name;
var h = document.querySelectorAll(".popup-description[data-for='" + n + "']");
if(h !== null){
for(var j = 0; j < h.length; j++){
var e = h.item(j);
if(e.getAttribute("data-selected-value") == v){
e.style.display = "block";
}
else{
e.style.display = "none";
}
}
}
}
});
}
}
})();
.popup-description{
display: none;
}
<form>
Select Gender
<br />
<input type="radio" name="gender" id="male" value="male">
<label for="male">Male</label>
<p class="popup-description" data-for="gender" data-selected-value="male">
This text is shown when the user selects <b>male</b>.
</p>
<br />
<input type="radio" name="gender" id="female" value="female">
<label for="female">Female</label>
<p class="popup-description" data-for="gender" data-selected-value="female">
This text is shown when the user selects <b>female</b>.
</p>
<br />
</form>