簡體   English   中英

如何識別是否以編程方式檢查了無線電?

[英]How to identify whether or not a radio has been checked programmatically?

我有一個表單頁面,用戶可以在其中輸入ID,並從mysql中提取相應的配置文件數據並顯示在表單中,以便用戶可以編輯它。

一個元素是一組無線電,因此您可以選擇年級(即“1”,“2”,“3”等)。

當用戶提供ID時,將進行AJAX調用以使用數據預填充表單,包括選擇適當的無線電。

問題:

用戶必須選擇年級才能提交表單。 我用verifyForm()方法檢查:

function verifyForm() {
    if( !document.addStudentForm.elements["yearLevel"].checked ) {
        alert( "You must select a year level before submitting." );
        return false;
    }
};

我希望這可以檢查yearLevel ,如果沒有選擇選項,則alert / return false。

但是,當AJAX數據預先選擇yearLevel無線電時,這仍然表現為用戶沒有選擇無線電。

收音機由js通過以下代碼填充:

document.getElementById( "yearLevel_<?=$student['student']->get('yearLevel')?>" ).checked = true;

編輯:這是相關的HTML。

<form name="addStudentForm" action="validation/updateStudentValidate.php" method="POST" onSubmit="return verifyForm()">                                 
    <input type="radio" value="1" name="yearLevel" disabled id="yearLevel_1" /> 1
    <input type="radio" value="2" name="yearLevel" disabled id="yearLevel_2" /> 2
    <input type="radio" value="3" name="yearLevel" disabled id="yearLevel_3" /> 3
    <input type="radio" value="4" name="yearLevel" disabled id="yearLevel_4" /> 4
    <input type="radio" value="5" name="yearLevel" disabled id="yearLevel_5" /> 5
    <input type="radio" value="6" name="yearLevel" disabled id="yearLevel_6" /> 6
</form>

題:

我怎樣才能讓我的javascript正確識別無線電是否已被檢查,無論是手動還是以編程方式選擇?

這個StackOverflow帖子中獲取並適用於此示例和速度,您可以在AJAX成功返回中獲得:

var radios = document.getElementsByName('yearLevel'),
    i = radios.length,
    isChecked = false;

while(i--){
    if (radios[i].checked) {
        isChecked = true;
        break;
    }
}

然后當調用該函數時:

function verifyForm(){
    if(!isChecked){
        alert( "You must select a year level before submitting." );
        return false;
    }
};

這假設您的HTML中沒有名稱為yearLevel任何其他項。

這實際上會返回值,我想我不確定你是否想要查看特定項目,或者只是它們已被檢查過。 這個功能可以做到這兩點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM