使用 onChange 清除多个选择和复选框

Clearing multiple selects and check-boxes using onChange

本文关键字:选择 复选框 onChange 清除 使用      更新时间:2024-06-19

我有一个表单,其中包含 3 个选择框、8 个复选框和 1 个文本字段。

第二个和第三个选择框由先前的选择填充:选择 1 个填充 选择 2选择 2 个填充 选择 3。

当我更改选择2时,选择3将清除...完善!但是,当我更改选择 1 时,只有选择 2 清除。选择 3 仍具有值。

<html>
<select id="subject_select" name="subjects" class="chosen-select" data-    placeholder="Select a Subject" style="width:100%;font-size:.85em;" onchange="subject(this.value)">
<option></option>
<option value="1"></option>
<option> ...
</select>
<div id="subject"><select id="subjects_select" class="chosen-select" data-placeholder="Select a Grade" style="width:100%;font-size:.85em;" ></select></div>    
<div id="grade"><select id="standards_select" class="chosen-select" multiple data-placeholder="Select Standard(s)"></select></div>

我的JavaScript是:

function subject(str) {
    if (str == "") {
        return;
    } else { 
        if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    document.getElementById("subject").innerHTML = xmlhttp.responseText;
                    $("#subjects_select").chosen();
                }
            }
            xmlhttp.open("GET","subject_get.php?subj="+str,true);
            xmlhttp.send();
        }
    }

我试过使用document.getElementById('standards_select').value = "";function clear(val) {}onfocus="this.form.reset()"一样无济于事。

有人可以建议我哪里出错了吗?请不要直接回答这个问题。

我认为您的示例代码缺少相关部分。但是,您可以通过在 subject 发生更改时手动触发更改事件来修复它:

document.getElementById('standards_select').dispatchEvent(new Event("change"));

当选择 1 发生更改时,这将额外触发选择 2 的常用更改侦听器。