如何通过使用javascript仅知道select标记的id来获取下拉列表中选项的值

时间:2013-12-06 07:50:47

标签: javascript

这是我的js代码:

 var currentsecondarycategory = document.getElementById("se_category");
if(currentsecondarycategory.childElementCount > 1)
{
    if(!currentsecondarycategory.value.match(whiteSpaceRegExp))
    {
        error = 1;
        alert("please enter a secondary category for the Item.");
        currentElement.select();
        currentElement.focus();
        return;
    }
}

我想检查它们是否只有一个选项,然后如何检查该选项的值,这样如果它不是“找不到记录”的值,那么我可以将上面的第二条if条件应用于选项也。请帮助我。  这里的选项是动态的,因此无法通过单个ID进行检查。

3 个答案:

答案 0 :(得分:0)

使用.value的{​​{1}}属性。这是一个展示过程的jsfiddle:

http://jsfiddle.net/2nNy3/

HTML

currentsecondarycategory

JS

<select id="dropdown"><option value="test">that's the value</option></select>

如果您想获取console.log(document.getElementById("dropdown").value); 标签的文字,请使用:

option

答案 1 :(得分:0)

使用currentsecondarycategory.childNodes获取<option>中的<select>个节点。如果只有一个选项,则为currentsecondarycategory.childNodes[0],其值为currentsecondarycategory.childNodes[0].value

答案 2 :(得分:0)

var currentsecondarycategory = document.getElementById("se_category");
if(currentsecondarycategory.selectedIndex == 0){
    alert('put your message here');
    return false;
}

currentsecondarycategory.selectedIndex 它将返回选择框的选定索引

请尝试这个......可能会有所帮助