jquery selectedIndex doesn't work

六眼飞鱼酱① 提交于 2021-02-17 05:40:07

问题


i have a from with many select tags , when the user submit the form i want to check if the user choose one option for all the select tags and this is my jquery code

$('#apForm select').each(function(){
            var $this = $(this);
            if ($this.selectedIndex == 0){
                var error = 'fill this please' ;
                $this.next('span').text(error);
                errorCount = errorCount + 1;   
            }
        });

and i tried like this

$this.attr("selectedIndex")

i just give you the piece of my code where my question is if i should give more code tell me

thank you for help


回答1:


var $this = $(this);
if($this.get(0).selectedIndex == 0) {

}

or just simple

this.selectedIndex; // not $this / $(this)

If no option it will return -1

here I showed all above cases




回答2:


It's this.selectedIndex, not $this.selectedIndex :)

  • this is the HTMLDomElement
  • $this is jQuery object



回答3:


If you are using a version of jQuery above 1.6? then you can use

if ( $this.prop('selectedindex') == 0 ){ /* handle */ }


来源:https://stackoverflow.com/questions/10652063/jquery-selectedindex-doesnt-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!