JQuery - 如何根据值选择下拉项

发布于 2024-12-24 22:08:31 字数 371 浏览 1 评论 0原文

我想设置一个下拉列表(选择)以根据条目的值进行更改。

我有

<select id="mySelect">
  <option value="ps">Please Select</option>
  <option value="ab">Fred</option>
  <option value="fg">George</option>
  <option value="ac">Dave</option>
</select>

而且我知道我想更改下拉列表,以便选择值为“fg”的选项。我怎样才能用 JQuery 做到这一点?

I want set a dropdown(select) to be change based on the value of the entries.

I have

<select id="mySelect">
  <option value="ps">Please Select</option>
  <option value="ab">Fred</option>
  <option value="fg">George</option>
  <option value="ac">Dave</option>
</select>

And I know that I want to change the dropdown so that the option with the value of "fg" is selected. How can I do this with JQuery?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

虐人心 2024-12-31 22:08:31

您应该使用

$('#dropdownid').val('selectedvalue');

以下示例:

$('#dropdownid').val('selectedvalue');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='dropdownid'>
    <option value=''>- Please choose -</option>
    <option value='1'>1</option>
    <option value='2'>2</option>
    <option value='selectedvalue'>There we go!</option>
    <option value='3'>3</option>
    <option value='4'>4</option>
    <option value='5'>5</option>
</select>

You should use

$('#dropdownid').val('selectedvalue');

Here's an example:

$('#dropdownid').val('selectedvalue');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='dropdownid'>
    <option value=''>- Please choose -</option>
    <option value='1'>1</option>
    <option value='2'>2</option>
    <option value='selectedvalue'>There we go!</option>
    <option value='3'>3</option>
    <option value='4'>4</option>
    <option value='5'>5</option>
</select>

浪漫人生路 2024-12-31 22:08:31
$('#yourdropddownid').val('fg');

(可选)

$('select>option:eq(3)').attr('selected', true);

其中 3 是所需选项的索引。

现场演示

$('#yourdropddownid').val('fg');

Optionally,

$('select>option:eq(3)').attr('selected', true);

where 3 is the index of the option you want.

Live Demo

汹涌人海 2024-12-31 22:08:31
$('#mySelect').val('fg');...........
$('#mySelect').val('fg');...........
☆獨立☆ 2024-12-31 22:08:31
 $('#mySelect').val('ab').change();

 // or

 $('#mySelect').val('ab').trigger("change");
 $('#mySelect').val('ab').change();

 // or

 $('#mySelect').val('ab').trigger("change");
滥情稳全场 2024-12-31 22:08:31

你可以使用这个 jQuery 代码,我发现它更容易使用:

$('#your_id [value=3]').attr('selected', 'true');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="your_id" name="name" class="form-control input-md">
  <option value="1">Option #1</option>
  <option value="2">Option #2</option>
  <option value="3">Option #3</option>
  <option value="4">Option #4</option>
  <option value="5">Option #5</option>
  <option value="6">Option #6</option>
  <option value="7">Option #7</option>
</select>

You can use this jQuery code which I find it eaiser to use:

$('#your_id [value=3]').attr('selected', 'true');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="your_id" name="name" class="form-control input-md">
  <option value="1">Option #1</option>
  <option value="2">Option #2</option>
  <option value="3">Option #3</option>
  <option value="4">Option #4</option>
  <option value="5">Option #5</option>
  <option value="6">Option #6</option>
  <option value="7">Option #7</option>
</select>

罪#恶を代价 2024-12-31 22:08:31

您可以简单地使用:

$('#select_id').val('fg')

You can simply use:

$('#select_id').val('fg')
寻梦旅人 2024-12-31 22:08:31

在你的情况下 $("#mySelect").val("fg") :)

In your case $("#mySelect").val("fg") :)

笔芯 2024-12-31 22:08:31

回答可能为时已晚,但至少有人会得到帮助。

您可以尝试两种选择:

这是当您想要基于索引值进行分配时的结果,其中“0”是索引。

 $('#mySelect').prop('selectedIndex', 0);

不要使用“attr”,因为最新的 jquery 已弃用它。

当您想根据选项值进行选择时,请选择以下选项:

 $('#mySelect').val('fg');

其中“fg”是选项值

May be too late to answer, but at least some one will get help.

You can try two options:

This is the result when you want to assign based on index value, where '0' is Index.

 $('#mySelect').prop('selectedIndex', 0);

don't use 'attr' since it is deprecated with latest jquery.

When you want to select based on option value then choose this :

 $('#mySelect').val('fg');

where 'fg' is the option value

枯叶蝶 2024-12-31 22:08:31
$('#dropdownid').val('selectedvalue');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='dropdownid'>
    <option value=''>- Please choose -</option>
    <option value='1'>1</option>
    <option value='2'>2</option>
    <option value='selectedvalue'>There we go!</option>
    <option value='3'>3</option>
    <option value='4'>4</option>
    <option value='5'>5</option>
</select>

$('#dropdownid').val('selectedvalue');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='dropdownid'>
    <option value=''>- Please choose -</option>
    <option value='1'>1</option>
    <option value='2'>2</option>
    <option value='selectedvalue'>There we go!</option>
    <option value='3'>3</option>
    <option value='4'>4</option>
    <option value='5'>5</option>
</select>

零崎曲识 2024-12-31 22:08:31

这段代码对我有用:

$(function() {
    $('[id=mycolors] option').filter(function() { 
        return ($(this).text() == 'Green'); //To select Green
    }).prop('selected', true);
});

使用这个 HTML 选择列表:

<select id="mycolors">
      <option value="1">Red</option>
      <option value="2">Green</option>
      <option value="3">Blue</option>
</select>

This code worked for me:

$(function() {
    $('[id=mycolors] option').filter(function() { 
        return ($(this).text() == 'Green'); //To select Green
    }).prop('selected', true);
});

With this HTML select list:

<select id="mycolors">
      <option value="1">Red</option>
      <option value="2">Green</option>
      <option value="3">Blue</option>
</select>
止于盛夏 2024-12-31 22:08:31

我有一种不同的情况,下拉列表值已经被硬编码。只有 12 个区,因此 jQuery Autocomplete UI 控件不由代码填充。

解决方案要容易得多。因为我不得不费力地浏览其他帖子,其中假设控件是动态加载的,没有找到我需要的东西,然后最终弄清楚了。

因此,如果您有如下所示的 HTML,请像这样设置所选索引,请注意 -input 部分,它是除了下拉 id 之外的部分:

$('#project-locationSearch-dist-input').val('1');

                <label id="lblDistDDL" for="project-locationSearch-input-dist" title="Select a district to populate SPNs and PIDs or enter a known SPN or PID." class="control-label">District</label>
                <select id="project-locationSearch-dist" data-tabindex="1">
                    <option id="optDistrictOne" value="01">1</option>
                    <option id="optDistrictTwo" value="02">2</option>
                    <option id="optDistrictThree" value="03">3</option>
                    <option id="optDistrictFour" value="04">4</option>
                    <option id="optDistrictFive" value="05">5</option>
                    <option id="optDistrictSix" value="06">6</option>
                    <option id="optDistrictSeven" value="07">7</option>
                    <option id="optDistrictEight" value="08">8</option>
                    <option id="optDistrictNine" value="09">9</option>
                    <option id="optDistrictTen" value="10">10</option>
                    <option id="optDistrictEleven" value="11">11</option>
                    <option id="optDistrictTwelve" value="12">12</option>
                </select>

关于自动完成控件的其他问题是如何正确禁用/清空它。我们有 3 个控件一起工作,其中 2 个是相互排斥的:

//SPN
spnDDL.combobox({
    select: function (event, ui) {
        var spnVal = spnDDL.val();
        //fire search event
        $('#project-locationSearch-pid-input').val('');
        $('#project-locationSearch-pid-input').prop('disabled', true);
        pidDDL.empty(); //empty the pid list
    }
});
//get the labels so we have their tool tips to hand.
//this way we don't set id values on each label
spnDDL.siblings('label').tooltip();

//PID
pidDDL.combobox({
    select: function (event, ui) {
        var pidVal = pidDDL.val();
        //fire search event
        $('#project-locationSearch-spn-input').val('');
        $('#project-locationSearch-spn-input').prop('disabled', true);
        spnDDL.empty(); //empty the spn list
    }
});

其中一些超出了帖子的范围,我不知道到底该把它放在哪里。由于这非常有帮助并且花了一些时间才弄清楚,因此将其共享。

另外...要启用这样的控件,它是(禁用,假)而不是(启用,真)——这也花了一些时间来弄清楚。 :)

除了这篇文章之外,唯一需要注意的是:

    /*
Note, when working with the jQuery Autocomplete UI control,
the xxx-input control is a text input created at the time a selection
from the drop down is picked.  Thus, it's created at that point in time
and its value must be picked fresh.  Can't be put into a var and re-used
like the drop down list part of the UI control.  So you get spnDDL.empty()
where spnDDL is a var created like var spnDDL = $('#spnDDL);  But you can't
do this with the input part of the control.  Winded explanation, yes.  That's how
I have to do my notes or 6 months from now I won't know what a short hand note means
at all. :) 
*/
    //district
    $('#project-locationSearch-dist').combobox({
        select: function (event, ui) {
            //enable spn and pid drop downs
            $('#project-locationSearch-pid-input').prop('disabled', false);
            $('#project-locationSearch-spn-input').prop('disabled', false);
            //clear them of old values
            pidDDL.empty();
            spnDDL.empty();
            //get new values
            GetSPNsByDistrict(districtDDL.val());
            GetPIDsByDistrict(districtDDL.val());
        }
    });

所有内容都是共享的,因为即时学习这些东西花了太长时间。希望这有帮助。

I have a different situation, where the drop down list values are already hard coded. There are only 12 districts so the jQuery Autocomplete UI control isn't populated by code.

The solution is much easier. Because I had to wade through other posts where it was assumed the control was being dynamically loaded, wasn't finding what I needed and then finally figured it out.

So where you have HTML as below, setting the selected index is set like this, note the -input part, which is in addition to the drop down id:

$('#project-locationSearch-dist-input').val('1');

                <label id="lblDistDDL" for="project-locationSearch-input-dist" title="Select a district to populate SPNs and PIDs or enter a known SPN or PID." class="control-label">District</label>
                <select id="project-locationSearch-dist" data-tabindex="1">
                    <option id="optDistrictOne" value="01">1</option>
                    <option id="optDistrictTwo" value="02">2</option>
                    <option id="optDistrictThree" value="03">3</option>
                    <option id="optDistrictFour" value="04">4</option>
                    <option id="optDistrictFive" value="05">5</option>
                    <option id="optDistrictSix" value="06">6</option>
                    <option id="optDistrictSeven" value="07">7</option>
                    <option id="optDistrictEight" value="08">8</option>
                    <option id="optDistrictNine" value="09">9</option>
                    <option id="optDistrictTen" value="10">10</option>
                    <option id="optDistrictEleven" value="11">11</option>
                    <option id="optDistrictTwelve" value="12">12</option>
                </select>

Something else figured out about the Autocomplete control is how to properly disable/empty it. We have 3 controls working together, 2 of them mutually exclusive:

//SPN
spnDDL.combobox({
    select: function (event, ui) {
        var spnVal = spnDDL.val();
        //fire search event
        $('#project-locationSearch-pid-input').val('');
        $('#project-locationSearch-pid-input').prop('disabled', true);
        pidDDL.empty(); //empty the pid list
    }
});
//get the labels so we have their tool tips to hand.
//this way we don't set id values on each label
spnDDL.siblings('label').tooltip();

//PID
pidDDL.combobox({
    select: function (event, ui) {
        var pidVal = pidDDL.val();
        //fire search event
        $('#project-locationSearch-spn-input').val('');
        $('#project-locationSearch-spn-input').prop('disabled', true);
        spnDDL.empty(); //empty the spn list
    }
});

Some of this is beyond the scope of the post and I don't know where to put it exactly. Since this is very helpful and took some time to figure out, it's being shared.

Und Also ... to enable a control like this, it's (disabled, false) and NOT (enabled, true) -- that also took a bit of time to figure out. :)

The only other thing to note, much in addition to the post, is:

    /*
Note, when working with the jQuery Autocomplete UI control,
the xxx-input control is a text input created at the time a selection
from the drop down is picked.  Thus, it's created at that point in time
and its value must be picked fresh.  Can't be put into a var and re-used
like the drop down list part of the UI control.  So you get spnDDL.empty()
where spnDDL is a var created like var spnDDL = $('#spnDDL);  But you can't
do this with the input part of the control.  Winded explanation, yes.  That's how
I have to do my notes or 6 months from now I won't know what a short hand note means
at all. :) 
*/
    //district
    $('#project-locationSearch-dist').combobox({
        select: function (event, ui) {
            //enable spn and pid drop downs
            $('#project-locationSearch-pid-input').prop('disabled', false);
            $('#project-locationSearch-spn-input').prop('disabled', false);
            //clear them of old values
            pidDDL.empty();
            spnDDL.empty();
            //get new values
            GetSPNsByDistrict(districtDDL.val());
            GetPIDsByDistrict(districtDDL.val());
        }
    });

All shared because it took too long to learn these things on the fly. Hope this is helpful.

庆幸我还是我 2024-12-31 22:08:31

您可以按名称选择下拉选项值

// deom
jQuery("#option_id").find("option:contains('Monday')").each(function()
{
 if( jQuery(this).text() == 'Monday' )
 {
  jQuery(this).attr("selected","selected");
  }

});

You can select dropdown option value by name

// deom
jQuery("#option_id").find("option:contains('Monday')").each(function()
{
 if( jQuery(this).text() == 'Monday' )
 {
  jQuery(this).attr("selected","selected");
  }

});
千と千尋 2024-12-31 22:08:31
$('select#myselect option[value="ab"]')
$('select#myselect option[value="ab"]')
混吃等死 2024-12-31 22:08:31

两者均可用于获取所选选项值

$('#dropdownID').on('change', function () {
        var dropdownselected=$("#dropdownID option:selected").val();
        });
     
     or 
     
     $('#dropdownID').on('change', function () {
        var dropdownselected=this.selectedOptions[0].value;
     });

either can be used to get the selected option value

$('#dropdownID').on('change', function () {
        var dropdownselected=$("#dropdownID option:selected").val();
        });
     
     or 
     
     $('#dropdownID').on('change', function () {
        var dropdownselected=this.selectedOptions[0].value;
     });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文