在我的网络表单上,我有一个询问输入生日和性别的问题。
我想使用Javascript进行检查,以确保如果用户选择“男性”,则他必须年满18岁且未满55岁。但是,如果他们选择“女性”,则必须年满20岁且不超过50岁。
(我的HTML示例)我有:
<b>Gender: </b><br>
<input type="radio" name="Gender" value="male" required> Male
<input type="radio" name="Gender" value="female" required> Female
<br><br>
<b>Date of Birth: </b><br>
<input type="date" name="dob" required >
<br><br>
我该怎么做?
答案 0 :(得分:0)
由于没有任何有用的答案,所以我最终自己做了:
function checkGender() {
var test = document.getElementById("male").checked;
document.getElementById("demo").innerHTML = test;
if (test == true) {
ageMin = 18;
ageMax = 55;
} else {
ageMin = 20;
ageMax = 50;
}
//The following are only used to test that the values work
document.getElementById("demo1").innerHTML = ageMin;
document.getElementById("demo2").innerHTML = ageMax;
var dateString = document.getElementById("doB").value;
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth()- birthDate.getMonth();
document.getElementById("demo3").innerHTML = dateString;
document.getElementById("demo4").innerHTML = today;
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
document.getElementById("demo5").innerHTML = age;
if (age<ageMin || age>ageMax) {
alert("Age is outside limits, please try again.");
stop();
}
}
HTML方面的内容:
<div class="form-row">
<br>
<legend class="col-form-label col-sm-1 col-sm-offset-1">Gender:</legend>
<div class="col-sm-4">
<div class="form-check">
<input class="form-check-input" id="male" type="radio"
name="Gender" value="male" required checked name="gender">
<label class="form-check-label" for="male">
Male
</label>
</div>
<div class="form-check">
<input id="female" type="radio" name="Gender" value="female" required name="gender">
<label class="form-check-label" for="female">
Female
</label>
</div>
</div>
<div class="col-sm-4">
<label for="doB">Date of Birth:</label><br>
<input id="doB" type="date" name="dob" required>
</div>
</div>
答案 1 :(得分:-3)
HTMLElement
属性基本上,您要查找的是,当单击单选按钮时,它会触发一个函数,该函数然后修改属性min
并更改日期
maleRadioButton.addEventListener('click', () => dateInput.setAttribute('min', new Date(new Date().setFullYear(new Date().getFullYear() - 18)).toLocaleDateString())
仅供参考,我真诚地希望,针对不同性别使用不同年龄段的原因不是性别歧视。