Set select option 'selected', by value

2018-12-31 21:04发布

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 value of the option that must be selected?

I have the following HTML:

<div class="id_100">
  <select>
    <option value="val1">Val 1</option>
    <option value="val2">Val 2</option>
    <option value="val3">Val 3</option>
  </select>
</div>

I need to select the option with value val2. How can this be done?

Here's a demo page: http://jsfiddle.net/9Stxb/

21条回答
只若初见
2楼-- · 2018-12-31 21:55

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.

查看更多
美炸的是我
3楼-- · 2018-12-31 22:01
var opt = new Option(name, id);
$("#selectboxName").append(opt);
opt.setAttribute("selected","selected");
查看更多
残风、尘缘若梦
4楼-- · 2018-12-31 22:03

a simple answer is, at html

<select name="ukuran" id="idUkuran">
    <option value="1000">pilih ukuran</option>
    <option value="11">M</option>
    <option value="12">L</option>
    <option value="13">XL</option>
</select>

on jquery, call below function by button or whatever

$('#idUkuran').val(11).change();

it simple and 100% works, coz its taken from my work... :) hope its help..

查看更多
登录 后发表回答