按值设置“选定”选项。

时间:2022-11-27 21:56: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?

我有一个select字段,里面有一些选项。现在我需要用jQuery选择其中一个选项。但是,当我只知道必须选择的选项的值时,我该如何做呢?

I have the following HTML:

我有以下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?

我需要选择value val2的选项。这是怎么做到的呢?

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

这里有一个演示页面:http://jsfiddle.net/9Stxb/。

20 个解决方案

#1


1098  

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.

看看这个jQuery方法。

#2


300  

To select an option with value 'val2':

选择值为“val2”的选项:

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

#3


172  

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

选择值后使用change()事件。从文档:

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

如果字段在没有更改内容的情况下失去焦点,则不会触发事件。若要手动触发事件,请使用.change()而无需参数:

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

More information is at .change().

更多信息在.change()中。

#4


40  

Deselect all first and filter the selectable options:

首先取消选择,并筛选可选选项:

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

#5


36  

<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


28  

For me the following did the job

对我来说,接下来的工作就是这样。

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

#7


21  

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.

我认为最简单的方法是选择设置val(),但是您可以检查以下内容。了解如何处理jQuery中的select和option标记?有关选项的更多细节。

$('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


15  

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.

您可以通过使用属性选择器[attributename=optionalvalue]来选择任何属性及其值,因此在您的情况下,您可以选择该选项并设置所选的属性。

$("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


11  

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.

输出:这将激活ENT。

#10


9  

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

在设置了select值之后,最好使用change()。

$("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提琴中:

JS Fiddle

JS小提琴

#11


8  

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:

这适合我。我使用这个代码来解析fancybox更新表单中的一个值,而我的完整源代码来自app.js:

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:

我的PHP代码是:

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));
}

#12


7  

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

#13


7  

a simple answer is, at html

一个简单的答案是,在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

在jquery中,按按钮或其他函数调用下面的函数。

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

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

它简单而100%有效,因为它取自我的作品……:)希望它帮助. .

#14


6  

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

.attr()有时在旧的jQuery版本中不起作用,但您可以使用。prop():

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

#15


4  

This works for sure for Select Control:

这可以确保选择控制:

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

#16


2  

Just put in this code:

只需输入以下代码:

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

#17


2  

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

试试这个。简单而有效的javaScript + jQuery致命组合。

SelectComponent :

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.

现在您的选项4将被选中。您可以这样做,在默认情况下选择start的值。

$(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

或者创建一个简单的函数,将该行放入其中,并调用anyEvent上的函数来选择该选项。

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

jQuery + javaScript的混合物的魔法....

#18


1  

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

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

$(" # graphtype选项(value = " ")”)。道具(“选择”,真正的);这在#graphtype是select标记的id的地方很有效。

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>

#19


0  

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

这是一个古老的帖子,但这里有一个简单的功能,像jQuery插件。

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

Reson为什么要使用这个是因为你将选择的satemant改为DOM什么是交叉浏览器支持的,也会触发变化,你可以抓住它。

Is basicaly human action simulation.

是basicaly人体动作模拟。

#20


0  

Okay, I realize this post is ancient, but some of the responses on this are worse than bad. Scary even. And I'm resisting the urge not to answer this in pirate speak out of contempt for some of the other posters on this thread.

好吧,我知道这篇文章是很古老的,但是其中的一些反应比坏的更糟糕。甚至可怕。我拒绝回答这个问题,因为在这个帖子里,一些其他的海报被海盗们鄙视。

There's no reason to overthink this with endless finds and selects. This is really easy. All you're 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:

好的,一些基本的dom:如果你用的是纯Javascript,你会这样做:

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, god bless it, you want to use the .prop() function to set a property. I guess that makes sense. So, you would do it like this.

但你不是用纯Javascript,而是用Jquery。在Jquery中,上帝保佑它,你想要使用。prop()函数来设置属性。我想这是有道理的。你可以这样做。

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

See? Was that really so hard?

看到了吗?这真的很难吗?

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

不管怎样,只要确保你的id是唯一的。否则,你就会一头撞在墙上,想知道为什么这行不通。

#1


1098  

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.

看看这个jQuery方法。

#2


300  

To select an option with value 'val2':

选择值为“val2”的选项:

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

#3


172  

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

选择值后使用change()事件。从文档:

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

如果字段在没有更改内容的情况下失去焦点,则不会触发事件。若要手动触发事件,请使用.change()而无需参数:

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

More information is at .change().

更多信息在.change()中。

#4


40  

Deselect all first and filter the selectable options:

首先取消选择,并筛选可选选项:

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

#5


36  

<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


28  

For me the following did the job

对我来说,接下来的工作就是这样。

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

#7


21  

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.

我认为最简单的方法是选择设置val(),但是您可以检查以下内容。了解如何处理jQuery中的select和option标记?有关选项的更多细节。

$('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


15  

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.

您可以通过使用属性选择器[attributename=optionalvalue]来选择任何属性及其值,因此在您的情况下,您可以选择该选项并设置所选的属性。

$("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


11  

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.

输出:这将激活ENT。

#10


9  

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

在设置了select值之后,最好使用change()。

$("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提琴中:

JS Fiddle

JS小提琴

#11


8  

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:

这适合我。我使用这个代码来解析fancybox更新表单中的一个值,而我的完整源代码来自app.js:

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:

我的PHP代码是:

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));
}

#12


7  

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

#13


7  

a simple answer is, at html

一个简单的答案是,在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

在jquery中,按按钮或其他函数调用下面的函数。

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

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

它简单而100%有效,因为它取自我的作品……:)希望它帮助. .

#14


6  

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

.attr()有时在旧的jQuery版本中不起作用,但您可以使用。prop():

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

#15


4  

This works for sure for Select Control:

这可以确保选择控制:

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

#16


2  

Just put in this code:

只需输入以下代码:

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

#17


2  

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

试试这个。简单而有效的javaScript + jQuery致命组合。

SelectComponent :

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.

现在您的选项4将被选中。您可以这样做,在默认情况下选择start的值。

$(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

或者创建一个简单的函数,将该行放入其中,并调用anyEvent上的函数来选择该选项。

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

jQuery + javaScript的混合物的魔法....

#18


1  

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

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

$(" # graphtype选项(value = " ")”)。道具(“选择”,真正的);这在#graphtype是select标记的id的地方很有效。

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>

#19


0  

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

这是一个古老的帖子,但这里有一个简单的功能,像jQuery插件。

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

Reson为什么要使用这个是因为你将选择的satemant改为DOM什么是交叉浏览器支持的,也会触发变化,你可以抓住它。

Is basicaly human action simulation.

是basicaly人体动作模拟。

#20


0  

Okay, I realize this post is ancient, but some of the responses on this are worse than bad. Scary even. And I'm resisting the urge not to answer this in pirate speak out of contempt for some of the other posters on this thread.

好吧,我知道这篇文章是很古老的,但是其中的一些反应比坏的更糟糕。甚至可怕。我拒绝回答这个问题,因为在这个帖子里,一些其他的海报被海盗们鄙视。

There's no reason to overthink this with endless finds and selects. This is really easy. All you're 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:

好的,一些基本的dom:如果你用的是纯Javascript,你会这样做:

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, god bless it, you want to use the .prop() function to set a property. I guess that makes sense. So, you would do it like this.

但你不是用纯Javascript,而是用Jquery。在Jquery中,上帝保佑它,你想要使用。prop()函数来设置属性。我想这是有道理的。你可以这样做。

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

See? Was that really so hard?

看到了吗?这真的很难吗?

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

不管怎样,只要确保你的id是唯一的。否则,你就会一头撞在墙上,想知道为什么这行不通。