繁体   English   中英

如果选中两个单选按钮之一,则标记为true

[英]Mark as true if one of the two radio buttons are checked

这可能是一件容易的事,但是我还没有弄清楚。 我有两个单选按钮,如果两个都选中,我想将状态设置为true。

for (let i = 0; i < inputs.length; i += 1) {
    if (
        inputs[i].name === 'person' &&
        ((inputs[i].value === 'Employee' && inputs[i].checked === true) ||
        (inputs[i].value === 'Dependent' && inputs[i].checked === true))
       ) {
        inputs[i].style.border = '';
        this.setState({ personFilled: true });
    } else if (
        inputs[i].name === 'person' &&
        ((inputs[i].value === 'Employee' && inputs[i].checked === false) ||
        (inputs[i].value === 'Dependent' && inputs[i].checked === false))) {
        inputs[i].style.border = '2px solid red';
    }
 }

截至目前,根据我的条件,它始终为假。

单选按钮代码

<label>Person</label>
<input
    type='radio'
    className='form-radio'
    name='person'
    id='person'
    value='Employee'
    onChange={gatherFormData}
/>
<span className='label'>Employee</span>
<input
    type='radio'
    className='form-radio'
    name='person'
    value='Dependent'
    onChange={gatherFormData}
/>
<span className='label'>Dependent</span>

您忘记将状态设置为false。 该代码可以简化为:

for (let i = 0; i < inputs.length; i += 1) {
  if (inputs[i].name === 'person') {
    const checked = ((inputs[i].value === 'Employee' && inputs[i].checked) || (inputs[i].value === 'Dependent' && inputs[i].checked));
    inputs[i].style.border = checked ? '' : '2px solid red';
    this.setState({ personFilled: checked });
  }
}

请注意,您正在循环中设置状态,因此在每次迭代时都将其值覆盖。 您可以将填充的人员存储为数组,或者根据索引存储不同的项目。 如果您的输入仅在UI中存在一次,则不应使用for循环并按id引用它们,如注释中所述。

只需使用Array.prototype.some()

if ([...inputs].some(x=>x.checked)) { this.setState({ personFilled: true }) };

假设inputs包含相关单选按钮的NodeList

我稍微修改了您的代码并添加了一些HTML,它对我来说像这样:

 function handler() { this.setState = function(state) { console.log(state); } inputs = document.querySelectorAll('input'); for (let i = 0; i < inputs.length; i += 1) { if (inputs[i].name === 'person' && ((inputs[i].value === 'Employee' && inputs[i].checked === true) || (inputs[i].value === 'Dependent' && inputs[i].checked === true)) ) { inputs[i].style.border = ''; this.setState({ personFilled: true }); } else if (inputs[i].name === 'person' && ((inputs[i].value === 'Employee' && inputs[i].checked === false) || (inputs[i].value === 'Dependent' && inputs[i].checked === false)) ) { inputs[i].style.border = '2px solid red'; } } } var element = document.querySelector('button') if (element.addEventListener) { element.addEventListener('click', handler, false); } else { element.attachEvent('onclick', handler); } 
 <input name="person" type="radio" value="Employee">Employee</input> <input name="person" type="radio" value="Dependent">Dependent</input> <button>Submit</button> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM