【问题标题】:How I can get all the values of select tag if 'id' of select tag is dynamic?如果选择标签的“id”是动态的,我如何获取选择标签的所有值?
【发布时间】:2021-07-28 12:30:56
【问题描述】:

问题:我有下拉菜单(一页上大约 10 个,每个都有不同的 id )。我正在尝试自动化这些控制字段,我需要在其中设置下拉菜单的值,并且我正在尝试为所有下拉菜单实施通用解决方案。

例如:对于给定的下拉菜单,我想将其值设置为韩语(ECU-KR)。

我的方法: 为了自动化这个下拉菜单,我试图获取选择标签的所有值并迭代每个值以与需要的值(我想在下拉菜单中设置(韩语(ECU-KR))进行比较)。但是我卡在这里.....

需要帮助:

  1. 如何获取选择标签的“id”?

  2. 如果我得到 id,那么我如何获取特定选择标签的所有值?

【问题讨论】:

    标签: javascript select dropdown selector


    【解决方案1】:
    let x = document.getElementById("57:").selectedIndex;
    let values = document.getElementsByTagName("option")[x].value;```
    

    这应该为你做到这一点。

    【讨论】:

    • id 不固定,所有下拉菜单都不同,想要实现一个通用的解决方案
    【解决方案2】:

    您可以通过 getElementById 获取元素。可以通过下拉列表的值检索选定的值。 options 属性包含数组,其中包含在下拉列表中找到的所有选项,因此您可以遍历它们并获取它们的值。

    function onChange(event) {
      const id = event.id;
      console.log(id);
      var select = document.getElementById(id);
      console.log("selected = " + select.value);
      var options= new Array();
      for (i = 0; i < select.options.length; i++) {
       options[i] = select.options[i].value;
      }
      console.log("options = " + options)
    }
    <select id="57" onchange="onChange(this)">
      <option value="UTF-8">UTF-8</option>
      <option value="ISO-859">ISO-859</option>
      <option value="euc-kr">euc-kr</option>
    </select>

    【讨论】:

    • id 不固定,所以 id =57 无法实现这个逻辑
    • 我更改了代码,所以它不固定。现在看看@RaviSharma
    【解决方案3】:

    获取选择器的id

    假设您已经有一个名为selector 的变量,那么它的id 可以由selector.id 确定。

    获取所有选择的ID

    for (let select of document.querySelectorAll('select')) {
        //do something with select.id
    }
    

    通过 id 模式获取选择

    由于您的id 包含冒号,我将假设您感兴趣的select 标签在其id 中都有冒号。在这种情况下:

    for (let select of document.querySelectorAll('select[id*=":"]')) {
        //Do something with select.id
    }
    

    *= 是包含选择器。

    获取具有某些 id 模式的选择的值

    let values = {};
    for (let select of document.querySelectorAll('select[id*=":"]')) {
        values[select.id] = [];
        for (let option of select.querySelectorAll('option')) {
            values.push(option.value);
        }
    }
    

    【讨论】:

      【解决方案4】:

      假设您知道要设置的值——并且假设只有一个 &lt;option&gt; 元素具有该值——我建议不要担心 &lt;select&gt; 元素,而是专注于 &lt;option&gt;

      // select the <option> element by its value attribute:
      let option = document.querySelector('option[value="ECU-KR"]'),
          // if you still have need of the <select> element:
          select = option.closest('select');
      // set the selected property of the <option>:
      option.selected = true;
      

      【讨论】:

        猜你喜欢
        • 2013-04-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-27
        • 2020-06-26
        • 1970-01-01
        相关资源
        最近更新 更多