0

When an option is selected that wasn't previously, the onChangehandler can detect this. 如何检测预选选项(即,选择字段是否选择了任何选项)?没有jQuery这可能吗?此事件是否有处理程序,例如onSelected(与onSelect突出显示的文本不同)?

例子:

<select onSelected="FunctionRunIfOptionSelected()">
<option> ... </option>
...
</select>

预选选项将在页面加载时被选中。即,动态呈现 HTML:

<option selected> ... </option>
4

5 回答 5

0
var myselect = document.getElementByid('selectid');         
myselect.options[myselect.selectedIndex];
于 2013-07-29T19:12:44.277 回答
0

您可以检测选择字段是否没有像这样选择默认值:

var selects = document.getElementsByTagName("select");
for (i=0;i<selects.length;i++) {
    if (selects[i].selectedIndex != 0) {
        eval(selects[i].getAttribute("onSelected"));
    }
}
于 2013-07-29T19:14:37.960 回答
0

要在页面加载时测试所选选项,您需要在window.onload处理程序中捕获这些选项

加载页面后,您需要继续使用onChange处理程序,但使用selectedIndex属性来测试它是否填充了选项列表中的索引。

或者,在 HTML 中提供您的选项值并检查这些值本身。这将在扩展选项列表时允许确定性行为。

于 2013-07-29T19:17:35.213 回答
0

是的,使用.options[]and.selectedIndex方法,您可以像这样干净利落地处理这个问题:

HTML

<select name="select" id="select">
    <option value="">...</option>
    <option value="1">One</option>
    <option value="2" selected="selected">Two</option>
</select>

JavaScript

window.onload = function(){
    var select = document.getElementById("select"), selected = select.value;
    select.onchange = function(){
        var val = select.options[select.selectedIndex].value;
        if(val != selected) {
            alert("Another value " + val + " was selected, which is not the same as the default value of " + selected);
        } else {
            alert("Same value as the default of " + selected + " was selected");
        }
    };
};

在 JS 中,您可以根据需要检查和操作val变量。

于 2013-07-29T19:19:50.873 回答
0

如果我理解,任务是判断一个选项是否将所选属性硬编码到 HTML 中?如果是这样,这应该工作:

function test () {
    var opts = document.getElementById("myselect").options;
    var i, len = opts.length;
    for(i = 0; i < len; i++) {
        if (opts[i].getAttribute("selected" ) != null ) { // opts[i] has the selected attribute
            change_other_select(i); // pass the option index to your other function
            break;
        }
    }
}

window.onload = test;

诀窍是区分选定的属性和选定的属性,以及空值和空字符串。

于 2013-07-29T19:41:07.200 回答