是否有任何处理程序可以检测选择字段是否在没有jQuery的情况下选择了任何选项

时间:2013-07-29 19:07:25

标签: javascript javascript-events detect

如果选择了以前不是的选项,onChange处理程序可以检测到这一点。如何检测预选选项(即选择字段是否选择了任何选项)?没有jQuery这可能吗?此事件是否有处理程序,例如onSelected(与突出显示的文本的onSelect不同)?

示例:

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

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

<option selected> ... </option>

5 个答案:

答案 0 :(得分:0)

var myselect = document.getElementByid('selectid');         
myselect.options[myselect.selectedIndex];

答案 1 :(得分:0)

您可以检测选择字段是否没有选择默认值,如下所示:

var selects = document.getElementsByTagName("select");
for (i=0;i<selects.length;i++) {
    if (selects[i].selectedIndex != 0) {
        eval(selects[i].getAttribute("onSelected"));
    }
}

答案 2 :(得分:0)

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

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

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

答案 3 :(得分:0)

是的,使用.options[].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变量。

答案 4 :(得分: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;

诀窍是区分所选属性和所选属性,以及空值和空字符串之间的区别。

相关问题