开发者

javascript: firefox selectedIndex on combobox

I have a simple little combobox on my web page:

<select id="famNum" onchange="familySize()">
       <option value="0">0</option>
       <option value="1">1</option> <!-- etc -->
</select>

And if I use:

famNum.selectedIndex = 0;

it works fine in Safari but not in firefox. I even tried using jQuery:

$(开发者_Python百科'#famNum').selectedIndex = 0;

but still firefox won't do it. How can I get this to work in firefox? It keeps saying "famNum is not defined"


Only some browsers add all the elements that have an id to the window object. This is non-standard behaviour, and Firefox for example doesn't do that. To access the element you should use the getElementById method:

document.getElementById('famNum').selectedIndex = 0;

If you want to use jQuery, the call doesn't return an element, it returns a jQuery object. You can either use a jQuery method to set the attribute:

$('#famNum').attr('selectedIndex', 0);

or you can get the element out of the jQuery object:

$('#famNum')[0].selectedIndex = 0;


Internet Explorer startet to expose elements with ids or names as global objects. Safari seems to have adopted that behaviour. Use getElementById() to get it working on every browser.

document.getElementById("famNum").selectedIndex = 0;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜