【问题标题】:How to select option from dropdown with exact text如何从带有确切文本的下拉列表中选择选项
【发布时间】:2012-06-21 03:33:13
【问题描述】:

我想让用户输入一个文本框并在选择下拉列表中查找并选择它。但是我有对象本身而不是它的名字。

目前在文本框上按回车将运行以下代码

$(this).prev().find('option:contains(\'editboxValue\')').attr('selected', 'selected');

但上面的代码只选择了Text2。以下代码工作正常,但看起来很乱!

$(this).prev().find("option").each(function(){ if ($(this).text() == 'editboxValue') $(this).attr("selected","selected");});

有没有更好的写法?

<select>
  <option>Text</option>
  <option>Text1</option>
  <option>Text2</option>
</select>
<input type="text">

【问题讨论】:

  • 你的each 循环永远不会选择一个元素。 '+ $(this).val() +' 是字面意思。你可以使用filterapi.jquery.com/filter
  • @Felix:感谢您指出错误。我从附加到选择的部分事件中选择了这条线。我编辑了代码以显示我的意思

标签: jquery jquery-selectors


【解决方案1】:

要使用下拉列表项文本选择选项,请使用此

var findText = $('#textBoxId').val();
$('#dropDownList option').
    filter(function () {return ($(this).text() == findText); })).
    attr('selected', 'selected'); 

【讨论】:

    【解决方案2】:

    为您的选择提供一个 ID 或类别,并为您的选项提供与您的文本相同的 ID。 如果您生成选项,则易于制作。 你需要做的就是:

    var myId = 'GetTheIdYouNeed'
    $('.mySelect').find(myId);
    

    【讨论】:

    • 这将搜索具有标签名称 GetTheIdYouNeed的元素。
    • 不是这样,我可以在页面中有多个选择,每个选择后面都有文本框。事件在运行时附加到每个文本框,因此脚本未知
    猜你喜欢
    • 2019-07-05
    • 2017-05-19
    • 2017-10-17
    • 2021-10-05
    • 2020-01-11
    • 2016-06-28
    • 1970-01-01
    相关资源
    最近更新 更多