选项选择菜单,检测是否选择了第一个选项,而不是第一个选项的值

时间:2014-02-02 17:20:58

标签: javascript jquery

我正在尝试基于select选项运行一些代码,但不是选项值, 但是,如果它是第一个选项。这是因为代码将全局使用,并且选项值将根据用户所在的产品页面而有所不同。 我的伪代码:

if ( the first option.select 'selected' ) {
run some code;
    } else { 
run some other code;
} 

此项目的典型选择菜单如下所示:

<select name="id[1]" id="attrib-1">
  <option value="20" selected="selected">Please Select</option>
  <option value="212" >Green</option>
  <option value="208">Yellow</option>
  <option value="210">Orange</option>
  <option value="219">Pink</option>
</select>

谢谢你们!

2 个答案:

答案 0 :(得分:2)

var select = document.getElementById('attrib-1');

select.onchange = function () {
    if (this.selectedIndex === 0) {
        // run some code...
    } else {
        // run some other code...
    }
}

参考:HTMLSelectElement - Web API Interfaces | MDN

答案 1 :(得分:2)

$(document).ready(function () {
    $("#attrib-1").change(function () {
        if ($("#attrib-1 > option:first").is(":selected")) {
            alert("first");
        } else {
            //do other stuff
        }
    });
});

http://jsfiddle.net/ergec/Mf62M/

$(document).ready(function () {
    $("#attrib-1").change(function () {
        if ($("#attrib-1").prop("selectedIndex") === 0) {
            alert("first");
        } else {
            //do other stuff
        }
    });
});