如何通过将文本与纯 JavaScript 匹配来获取选择菜单中选项的索引?

发布于 2024-12-05 17:32:48 字数 412 浏览 1 评论 0原文

我有一个选择菜单,我需要根据选项元素的文本值动态选择选项。例如,我的选择如下所示:

<select id="names">
    <option value="">Please Select</option>
    <option value="1">John</option>
    <option value="2">Steve</option>
    <option value="3">Max</option>
</select>

如果我有字符串“Max”,我怎样才能获得该选项的索引为4,以便我可以使用JavaScript动态地将其设置为selectedIndex?

没有 jQuery。

I have a select menu and I need to dynamically select the option based on the text value of the option element. For example, my select looks like this:

<select id="names">
    <option value="">Please Select</option>
    <option value="1">John</option>
    <option value="2">Steve</option>
    <option value="3">Max</option>
</select>

If I have the string "Max", how can I get that the index of the option is 4 so I can dynamically set this as the selectedIndex with JavaScript?

No jQuery.

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

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

发布评论

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

评论(9

以酷 2024-12-12 17:32:49

试试这个,它应该找到然后在选择框中选择相关选项。

var searchtext = "max";
for (var i = 0; i < listbox.options.length; ++i) {
    if (listbox.options[i].text === searchtext) listbox.options[i].selected = true;
}

Try this, it should find and then select the relevant option in the select box.

var searchtext = "max";
for (var i = 0; i < listbox.options.length; ++i) {
    if (listbox.options[i].text === searchtext) listbox.options[i].selected = true;
}
九八野马 2024-12-12 17:32:49

您可以使用这个简短的函数来做到这一点:

function findIndexfromOptionName( select, optionName ) {
    let options = Array.from( select.options );
    return options.findIndex( (opt) => opt.label == optionName );
}

参数:

  • select:一个HTMLSelect元素
  • optionName< /code>:作为字符串

说明:
在函数体的第一行,我们使用 Array.from()< 以 array 形式检索

想要一些使用它的理由吗?
它的实现很短,语义也很清晰。也是纯JS。

You could use this short function to do that:

function findIndexfromOptionName( select, optionName ) {
    let options = Array.from( select.options );
    return options.findIndex( (opt) => opt.label == optionName );
}

Arguments:

  • select: an HTMLSelect element
  • optionName: as a string

Explanation:
On the first line of the function body we retrieve the <select> options as an array using Array.from().
This allow us to use Array.prototype.findIndex() to return the index of the first option that match the provided name, if any or return -1 if there is no match.

Want some reasons to use it ?
It has a short implementation and the semantic is pretty clear. Also pure JS.

看海 2024-12-12 17:32:49
var opts = document.getElementById("names").options;
for(var i = 0; i < opts.length; i++) {
    if(opts[i].innerText == "Max") {
        alert("found it at index " + i + " or number " + (i + 1));
        break;
    }
}

演示。

var opts = document.getElementById("names").options;
for(var i = 0; i < opts.length; i++) {
    if(opts[i].innerText == "Max") {
        alert("found it at index " + i + " or number " + (i + 1));
        break;
    }
}

Demo.

§普罗旺斯的薰衣草 2024-12-12 17:32:49

在普通js中

var sel, opts, opt, x, txt;
txt='Max';
sel=document.getElementById('names');
opts=sel.options;
for (x=0;x<opts.lenght;x++){
    if (opts[x].text === txt){
        opt=opts[x];
    }
}

in PLAIN js

var sel, opts, opt, x, txt;
txt='Max';
sel=document.getElementById('names');
opts=sel.options;
for (x=0;x<opts.lenght;x++){
    if (opts[x].text === txt){
        opt=opts[x];
    }
}
绝對不後悔。 2024-12-12 17:32:49

options 属性将选项存储在选择菜单中 - 迭代它并比较内容。

var list = document.getElementById("names").options;

for(var i = 0; i<list.length; i++){
    if(list[i].text== "Max") { //Compare
        list[i].selected = true; //Select the option.
    }
}

JSFiddle: http://jsfiddle.net/cuTxu/2

The options property stores the options in a select menu - iterate over it and compare the contents.

var list = document.getElementById("names").options;

for(var i = 0; i<list.length; i++){
    if(list[i].text== "Max") { //Compare
        list[i].selected = true; //Select the option.
    }
}

JSFiddle: http://jsfiddle.net/cuTxu/2

爱本泡沫多脆弱 2024-12-12 17:32:49

这应该可以解决问题:

var options = document.getElementsByTagName('select')[0].children,
    i,
    l = options.length,
    index;

for(i = 0; i < l; i++){
  if(options[i].firstChild.nodeValue === 'Max'){index = i};
}

请注意,索引是从零开始的,这意味着它比您预期的少一。

This should do the trick:

var options = document.getElementsByTagName('select')[0].children,
    i,
    l = options.length,
    index;

for(i = 0; i < l; i++){
  if(options[i].firstChild.nodeValue === 'Max'){index = i};
}

Please note that the index is zero based, what mean it is one less than you would expect.

尾戒 2024-12-12 17:32:49
var x = document.getElementById("names");
for(var i = 0; i<x.options.length; i++){
    if("Max" == x.options[i].text){
        doSomething();
        //maybe x.selectedIndex = i;
    }
}
var x = document.getElementById("names");
for(var i = 0; i<x.options.length; i++){
    if("Max" == x.options[i].text){
        doSomething();
        //maybe x.selectedIndex = i;
    }
}
滥情哥ㄟ 2024-12-12 17:32:49

[编辑 - 扩展为包括非 jquery 方法]

强烈建议为此使用 jQuery,因为该解决方案很简单:

jQuery('#names option:contains("Max")').val()

但是,无论如何,这里有一个纯 JavaScript 实现:

function findOption( select, matchMe ) {

  var

    // list of child options
    options = select.getElementsByTagName('option'),

    // iteration vars
    i = options.length,
    text,
    option;

  while (i--) {

    option = options[i];
    text = option.textContent || option.innerText || '';

    // (optional) add additional processing to text, such as trimming whitespace
    text = text.replace(/^\s+|\s+$/g);

    if (text === matchMe) {
      return option.getAttribute('value');
    }

  }

  return null;

}

用法示例:

alert(
  findOption(
    document.getElementsByTagName('select')[0],
    "Max"
  )
);

警报 3

[edit - expanded to include non-jquery method]

I strongly recommend using jQuery for this since the solution is a one-liner:

jQuery('#names option:contains("Max")').val()

However, here's a pure JavaScript implementation anyway:

function findOption( select, matchMe ) {

  var

    // list of child options
    options = select.getElementsByTagName('option'),

    // iteration vars
    i = options.length,
    text,
    option;

  while (i--) {

    option = options[i];
    text = option.textContent || option.innerText || '';

    // (optional) add additional processing to text, such as trimming whitespace
    text = text.replace(/^\s+|\s+$/g);

    if (text === matchMe) {
      return option.getAttribute('value');
    }

  }

  return null;

}

Example usage:

alert(
  findOption(
    document.getElementsByTagName('select')[0],
    "Max"
  )
);

Alerts 3

月竹挽风 2024-12-12 17:32:48

http://jsfiddle.net/x8f7g/1/

您想要选择该元素,迭代数组,找到文本值,并返回索引。

  • 不要使用 InnerHTML,它很慢且容易损坏,而且不符合标准
  • 不要使用 innerText,原因类似,但没有那么严重
  • 不要使用函数,这样您就可以重新做一遍。
  • 选择子文本节点,并检索节点值,这是跨浏览器友好的

示例:

function indexMatchingText(ele, text) {
    for (var i=0; i<ele.length;i++) {
        if (ele[i].childNodes[0].nodeValue === text){
            return i;
        }
    }
    return undefined;
}

http://jsfiddle.net/x8f7g/1/

You want to select the element, iterate over the array, find the text value, and return the index.

  • Don't use InnerHTML, it's slow and breaks and not standards compliant
  • Dont use innerText, simmilar reasons but not quite as serious
  • Do use a function so you can do it all over again.
  • Do select the child text node, and retreives the nodeValue, which is cross-browser friendly

Example:

function indexMatchingText(ele, text) {
    for (var i=0; i<ele.length;i++) {
        if (ele[i].childNodes[0].nodeValue === text){
            return i;
        }
    }
    return undefined;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文