Set select option 'selected', by value

2018-12-31 20:58发布

问题:

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/

回答1:

There\'s an easier way that doesn\'t require you to go into the options tag:

$(\"div.id_100 select\").val(\"val2\");

Check out the this jQuery method.



回答2:

To select an option with value \'val2\':

$(\'.id_100 option[value=val2]\').attr(\'selected\',\'selected\');


回答3:

Use the change() event after selecting the value. From the docs:

If the field loses focus without the contents having changed, the event is not triggered. To trigger the event manually, apply .change() without arguments:

$(\"#select_id\").val(\"val2\").change();

More information is at .change().



回答4:

Deselect all first and filter the selectable options:

$(\'.id_100 option\')
     .removeAttr(\'selected\')
     .filter(\'[value=val1]\')
         .attr(\'selected\', true)


回答5:

<select name=\"contribution_status_id\" id=\"contribution_status_id\" class=\"form-select\">
    <option value=\"1\">Completed</option>
    <option value=\"2\">Pending</option>
    <option value=\"3\">Cancelled</option>
    <option value=\"4\">Failed</option>
    <option value=\"5\">In Progress</option>
    <option value=\"6\">Overdue</option>
    <option value=\"7\">Refunded</option>

Setting to Pending Status by value

   $(\'#contribution_status_id\').val(\"2\");


回答6:

For me the following did the job

$(\"div.id_100\").val(\"val2\").change();


回答7:

I think the easiest way is selecting to set val(), but you can check the following. See How to handle select and option tag in jQuery? for more details about options.

$(\'div.id_100  option[value=\"val2\"]\').prop(\"selected\", true);

$(\'id_100\').val(\'val2\');

Not optimised, but the following logic is also useful in some cases.

$(\'.id_100 option\').each(function() {
    if($(this).val() == \'val2\') {
        $(this).prop(\"selected\", true);
    }
});


回答8:

You can select on any attribute and its value by using the attribute selector [attributename=optionalvalue], so in your case you can select the option and set the selected attribute.

$(\"div.id_100 > select > option[value=\" + value + \"]\").prop(\"selected\",true);

Where value is the value you wish to select by.

If you need to removed any prior selected values, as would be the case if this is used multiple times you\'d need to change it slightly so as to first remove the selected attribute

$(\"div.id_100 option:selected\").prop(\"selected\",false);
$(\"div.id_100 option[value=\" + value + \"]\")
        .prop(\"selected\",true);


回答9:

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..



回答10:

The easiest way to do that is:

HTML

<select name=\"dept\">
   <option value=\"\">Which department does this doctor belong to?</option>
   <option value=\"1\">Orthopaedics</option>
   <option value=\"2\">Pathology</option>
   <option value=\"3\">ENT</option>
</select>

jQuery

$(\'select[name=\"dept\"]\').val(\'3\');

Output: This will activate ENT.



回答11:

It\'s better to use change() after setting select value.

$(\"div.id_100 select\").val(\"val2\").change();

By doing this, the code will close to changing select by user, the explanation is included in JS Fiddle:

JS Fiddle



回答12:

Use:

$(\"div.id_100 > select > option[value=\" + value + \"]\").attr(\"selected\",true);

This works for me. I\'m using this code for parsing a value in a fancybox update form, and my full source from app.js is:

jQuery(\".fancybox-btn-upd\").click(function(){
    var ebid = jQuery(this).val();

    jQuery.ajax({
        type: \"POST\",
        url: js_base_url+\"manajemen_cms/get_ebook_data\",
        data: {ebookid:ebid},
        success: function(transport){
            var re = jQuery.parseJSON(transport);
            jQuery(\"#upd-kategori option[value=\"+re[\'kategori\']+\"]\").attr(\'selected\',true);
            document.getElementById(\"upd-nama\").setAttribute(\'value\',re[\'judul\']);
            document.getElementById(\"upd-penerbit\").setAttribute(\'value\',re[\'penerbit\']);
            document.getElementById(\"upd-tahun\").setAttribute(\'value\',re[\'terbit\']);
            document.getElementById(\"upd-halaman\").setAttribute(\'value\',re[\'halaman\']);
            document.getElementById(\"upd-bahasa\").setAttribute(\'value\',re[\'bahasa\']);

            var content = jQuery(\"#fancybox-form-upd\").html();
            jQuery.fancybox({
                type: \'ajax\',
                prevEffect: \'none\',
                nextEffect: \'none\',
                closeBtn: true,
                content: content,
                helpers: {
                    title: {
                        type: \'inside\'
                    }
                }
            });
        }
    });
});

And my PHP code is:

function get_ebook_data()
{
    $ebkid = $this->input->post(\'ebookid\');
    $rs = $this->mod_manajemen->get_ebook_detail($ebkid);
    $hasil[\'id\'] = $ebkid;
    foreach ($rs as $row) {
        $hasil[\'judul\'] = $row->ebook_judul;
        $hasil[\'kategori\'] = $row->ebook_cat_id;
        $hasil[\'penerbit\'] = $row->ebook_penerbit;
        $hasil[\'terbit\'] = $row->ebook_terbit;
        $hasil[\'halaman\'] = $row->ebook_halaman;
        $hasil[\'bahasa\'] = $row->ebook_bahasa;
        $hasil[\'format\'] = $row->ebook_format;
    }
    $this->output->set_output(json_encode($hasil));
}


回答13:

var opt = new Option(name, id);
$(\"#selectboxName\").append(opt);
opt.setAttribute(\"selected\",\"selected\");


回答14:

.attr() sometimes doesn\'t work in older jQuery versions, but you can use .prop():

$(\'select#ddlCountry option\').each(function () {
    if ($(this).text().toLowerCase() == co.toLowerCase()) {
        $(this).prop(\'selected\',\'selected\');
        return;
    }
});


回答15:

$(\'#graphtype option[value=\"\"]\').prop(\"selected\", true);

This works well where #graphtype is the id of the select tag.

example select tag:

 <select name=\"site\" id=\"site\" class=\"form-control\" onchange=\"getgraph1(this.options[this.selectedIndex].value);\">
    <option value=\"\" selected>Site</option> 
    <option value=\"sitea\">SiteA</option>
    <option value=\"siteb\">SiteB</option>
  </select>


回答16:

There\'s no reason to overthink this, all you are doing is accessing and setting a property. That\'s it.

Okay, so some basic dom: If you were doing this in straight JavaScript, it you would this:

window.document.getElementById(\'my_stuff\').selectedIndex = 4;

But you\'re not doing it with straight JavaScript, you\'re doing it with jQuery. And in jQuery, you want to use the .prop() function to set a property, so you would do it like this:

$(\"#my_stuff\").prop(\'selectedIndex\', 4);

Anyway, just make sure your id is unique. Otherwise, you\'ll be banging your head on the wall wondering why this didn\'t work.



回答17:

This works for sure for Select Control:

$(\'select#ddlCountry option\').each(function () {
if ($(this).text().toLowerCase() == co.toLowerCase()) {
    this.selected = true;
    return;
} });


回答18:

Just put in this code:

$(\"#Controls_ID\").val(value);


回答19:

Try this. Simple yet effective javaScript + jQuery the lethal combo.

SelectComponent :

<select id=\"YourSelectComponentID\">
            <option value=\"0\">Apple</option>
            <option value=\"2\">Banana</option>
            <option value=\"3\">Cat</option>
            <option value=\"4\">Dolphin</option>
</select>

Selection :

document.getElementById(\"YourSelectComponentID\").value = 4;

Now your option 4 will be selected. You can do this, to select the values on start by default.

$(function(){
   document.getElementById(\"YourSelectComponentID\").value = 4;
});

or create a simple function put the line in it and call the function on anyEvent to select the option

A mixture of jQuery + javaScript does the magic....



回答20:

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.



回答21:

  • You must take it in mind the value you want to change dynamically, must be same as one present in the options you define in your HTML as it is case sensative. You can change your select box dynamically as follows,

$(\"div#YOUR_ID\").val(VALUE_CHANGED).change(); //value must present in options you selected otherwise it will not work