![](/img/trans.png)
[英]How to stop form submission if one of two radio buttons are not checked by user
[英]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.