3 回答

TA貢獻2051條經驗 獲得超10個贊
<form name="formName">
<input type="radio" name="option1" id="option1" value="Right"/>Right
<input type="radio" name="option2" id="option2" value="Left"/>Left
</form>
<input onclick="checkResponse()" type="button" value="Continue" />
當用戶單擊繼續按鈕時,checkResponse函數將檢查是否選擇了任何選項。
<script type="text/javascript">
function checkResponse(){
if (isChecked('option1') || isChecked('option2')){
next();
}else{
alert("Your error message")
}
}
function isChecked(id){
return document.getElementById(id).checked; //returns true if any options are selected
}
</script>

TA貢獻1836條經驗 獲得超3個贊
我了解的是,如果未檢查任何內容,則需要顯示一個錯誤;如果檢查其中之一,則需要繼續。
為此,您將需要檢查是否選中了其中一個而不檢查其值,并為每個單選按鈕賦予唯一的ID。你可以做類似的事情
function isChecked(id){//Instead of filledOut
return document.getElementById(id).checked;
//.checked returns true or false
}
if (isChecked('option1') || isChecked('option2')){
next();
}else{
alert("Your error message")
}
如果需要,可以使用另一個函數來獲取值:
function getCheckedBtnValue(){
if(isChecked('option1')) return document.getElementById('option1').value
if(isChecked('option2')) return document.getElementById('option2').value
return null
}
//You can also use this function to check if any of them is checked
const value = getCheckedBtnValue();
if(value){
next();
}else{
alert("Your error message");
}
另外,請盡量不要在經常難以閱讀的HTML元素內編寫JavaScript。繼續使用JavaScript。
添加回答
舉報