Set select option 'selected', by value

后端 未结 28 2772
攒了一身酷
攒了一身酷 2020-11-22 10:40

I have a select field with some options in it. Now I need to select one of those options with jQuery. But how can I do that when I only know the

28条回答
  •  温柔的废话
    2020-11-22 11:29

    Is old post but here is one simple function what act like jQuery plugin.

        $.fn.selectOption = function(val){
            this.val(val)
            .find('option')
            .removeAttr('selected')
            .parent()
            .find('option[value="'+ val +'"]')
            .attr('selected', 'selected')
            .parent()
            .trigger('change');
    
            return this;
        };
    

    You just simple can do something like this:

    $('.id_100').selectOption('val2');
    

    Reson why use this is because you change selected satemant into DOM what is crossbrowser supported and also will trigger change to you can catch it.

    Is basicaly human action simulation.

提交回复
热议问题