当存在多个无线电组时,如何确定每个无线电组是否都有一个选定的无线电



晚上好,过去几天我一直在尝试如何用javascript验证多个无线电组。我的目的是确定用户是否做出了选择;如果没有,则通过错误消息提示他们。

我在Stack和谷歌等网站上搜索过,但无论我尝试/找到什么,我似乎都无法得到我想要的行为。到目前为止,我发现的问题/资源引导我找到了我目前的例子(如下所示(,但我希望你们中的一个可爱的人能引导我越过终点线。

具体来说,我正在寻找一个如何验证所有无线电组的示例,确保用户在每个无线电组中都做出了选择。(我很乐意对每一步进行很好的评论和解释,因为循环对我来说很难理解。(

提前感谢。😅👌

我在下面附上了一个完整的片段,里面有我的工作;我调整了这个片段,去掉了所有不重要的东西,希望它更容易理解。

编辑:忘记提及以下代码的问题。下面的代码似乎在某些选择组合上有效,但在其他选择组合上失败了,我怀疑这可能是一个循环错误,但当我认为我对它们理解不够好时,我会承认。

编辑:对于那些尚未到来的人,我接受了@KooiInc的回答,因为它回答了这个问题。虽然Jojo先生是正确的,但我应该使用表单和HTML5进行验证。愚蠢的疏忽最终让我浪费了大量的时间。😅啊,好吧,这都是一次学习经历。👍👌

示例代码段

class radioChecks {
// Constructor.
constructor() {
this.inputs = document.querySelectorAll("input");
this.radioGroups = document.querySelectorAll(".radioGroup");
this.errors = document.getElementById("errors");
this.bindEvents();
}
// Bind Events.
bindEvents() {
for (let i = 0; i < this.inputs.length; i++) {
this.inputs[i].addEventListener("click", function(e) {
if (e.target.dataset.direction) {
e.target.dataset.direction === "next"
this.validate();
}
}.bind(this));
}
}
validate() {
const _this = this;
function isRadioGroupValid() {
let checked = false;
let inputName = "";
for (let i = 0; i < _this.radioGroups.length; i++) {
const radios = _this.radioGroups[i].querySelectorAll('[type="radio"]');
for (let j = 0; j < radios.length; j++) {
radios[i].checked ? checked = true : checked = false;
inputName = radios[i].name;
}
}
!checked
?
_this.errorHandler(_this, `Please select an option for ${inputName}.`, true) :
_this.errorHandler(_this, "", false);
}
isRadioGroupValid();
console.log("All radio groups have selection.");
return true;
}
errorHandler(_this, message, error) {
// Show any errors.
function showErrors(message) {
_this.errors.innerHTML = message;
_this.errors.classList.add("invalid");
throw new Error(message);
}
// Clear any existing errors.
function clearErrors() {
_this.errors.innerHTML = "";
_this.errors.classList.remove("invalid");
}
// if error true. Show error.
error ? showErrors(message) : clearErrors();
}
}

new radioChecks();
* {
text-align: center;
box-sizing: border-box;
font-family: -apple-system, BlinkMacSystemFont, Arial, sans-serif;
}
.radioGroup {
display: flex;
justify-content: center;
align-items: center;
/* flex-flow: row nowrap; */
flex-direction: row;
flex-wrap: nowrap;
align-content: space-between;
gap: 1em;
max-width: 640px;
margin: 0 auto;
}
.radioGroup:first-of-type {
margin-top: 3em;
}
@media screen and (max-width: 768px) {
flex-direction: column;
}
.radioOption {
flex-grow: 1;
width: 100%;
margin-bottom: 1em;
}
input[type="radio"] {
position: absolute;
left: -9999px;
opacity: 0;
z-index: 100;
}
label {
display: block;
padding: 0.5em 1em;
border: 1px solid #999;
color: #999;
width: 100%;
cursor: pointer;
transition: all 0.2s ease;
}
input[type="radio"]:checked+label {
border: 1px solid #000;
color: #000;
transition: all 0.2s ease;
}
input[type="button"] {
margin-top: 3em;
background-color: #ddd;
border: none;
color: #000;
padding: 0.5em 2em;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
}
input[type="button"]:hover {
background-color: #ccc;
}
#errors.invalid {
display: block;
}
#errors {
display: none;
color: #842029;
background-color: #f8d7da;
border: 1px solid #f5c2c7;
font-weight: bold;
padding: 0.5em 2em;
width: 300px;
margin: 2em auto;
}
<div class="radioGroup">
<div class="radioOption">
<input type="radio" id="radioOne" name="group_one" value="Foo">
<label for="radioOne">My Foo Radio</label>
</div>
<div class="radioOption">
<input type="radio" id="radioTwo" name="group_one" value="Bar">
<label for="radioTwo">My Bar Radio</label>
</div>
</div>
<div class="radioGroup">
<div class="radioOption">
<input type="radio" id="radioThree" name="group_two" value="Baz">
<label for="radioThree">My Baz Radio</label>
</div>
<div class="radioOption">
<input type="radio" id="radioFour" name="group_two" value="Qux">
<label for="radioFour">My Qux Radio</label>
</div>
</div>
<div class="btn">
<input type="button" data-direction="next" value="Next" />
</div>
<div id="errors"> Testing! </div>

您可以使用css选择器来确定无线电检查状态。这里有一个最小的例子:

document.addEventListener(`click`, evt => {
if (evt.target.id === `allchecked`) {
console.clear();
const bothChecked = document
.querySelectorAll(`.rGroup input[type='radio']:checked`)
.length === 2;
console.log(`both groups checked? ${
bothChecked ? `Yep`: `Nope`}`);
}
})
<div class="rGroup" id="group1">
<input type="radio" name="rg1"> one
<input type="radio" name="rg1"> two
<input type="radio" name="rg1"> three
</div>
<div class="rGroup" id="group2">
<input type="radio" name="rg2"> one
<input type="radio" name="rg2"> two
<input type="radio" name="rg2"> three
</div>
<button id="allchecked">both checked?</button>

使用HTML5表单验证的示例代码:

const myForm = document.forms['my-form']
myForm.onsubmit = e =>
{
e.preventDefault() // disable form submitting
console.clear()
console.log(Object.fromEntries(new FormData(myForm).entries()))
}
myForm.reset =_=>
{
console.clear()
}
<form name="my-form">
<fieldset>
<legend> group A </legend>
<label><input type="radio" name="rg1" value="A_1" required> one  </label>
<label><input type="radio" name="rg1" value="A_2"> two  </label>
<label><input type="radio" name="rg1" value="A_3"> tree </label>
</fieldset>

<fieldset>
<legend> group B </legend>
<label><input type="radio" name="rg2" value="B_1" required> one  </label>
<label><input type="radio" name="rg2" value="B_2"> two  </label>
<label><input type="radio" name="rg2" value="B_3"> tree </label>
</fieldset>
<button> validation </button>
<button type="reset"> reset </button>

</form>

最新更新