有没有一种方法可以获取SELECT TAG中的所有选项值而无需ID?

时间:2019-06-14 08:54:07

标签: javascript jquery

您是否知道是否可以采用SELECT中包含的OPTION VALUE中的所有值? 我会给你一个例子,我有这个代码:

<SELECT onChange="chData(this,this.value)"> 
<OPTION VALUE=MIPS1 >MIPS
<OPTION VALUE=MSU1 >MSU
<OPTION VALUE=PERCEN1 >% CEC
<OPTION VALUE=NUMGCP1 >nCPU
</SELECT>

我只知道第一个值是MIPS1,我需要取其他值。这是一种写法,如果我知道第一个MIPS1,我将搜索?中包含的其他值。 在此先感谢:)

5 个答案:

答案 0 :(得分:1)

您可以使用以下方法获取具有特定值的选项的<select>元素:

const select = document.querySelector('option[value=MIPS1]').closest('select');

有了<select>元素后,您可以使用类似以下内容的方法来检索它的选项:

const options = select.querySelectorAll('option');

或者:

const options = select.options;

正如@charlietfl所述,并非所有浏览器都支持.closest,相反,您可以使用.parentElement

答案 1 :(得分:1)

jQuery版本

var opt = "MIPS1";
const $sel = $("option[value='"+opt+"']").parent()
const options = $("option",$sel).map(function() { return this.value }).get()
console.log(options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<SELECT onChange="chData(this,this.value)">
  <OPTION VALUE=MIPS1>MIPS
  <OPTION VALUE=MSU1>MSU
  <OPTION VALUE=PERCEN1>% CEC
  <OPTION VALUE=NUMGCP1>nCPU
</SELECT>

答案 2 :(得分:0)

以下示例显示了如何执行此操作。 jQuery已被完全注释。

让我知道这是否不是您想要的。


演示

// Create array
var options = [];

// Load option value you're looking for into a variable
var search_term = "MIPS1";

// Find option with known value, travel up DOM tree to select and then find all options within it
$("option[value='" + search_term + "']").closest("select").find("option").each(function() {

  // Add values to array
  options.push($(this).val());

});

// Print the array
console.log(options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<SELECT onChange="chData(this,this.value)">
  <OPTION VALUE=MIPS1>MIPS
  <OPTION VALUE=MSU1>MSU
  <OPTION VALUE=PERCEN1>% CEC
  <OPTION VALUE=NUMGCP1>nCPU
</SELECT>

答案 3 :(得分:0)

这将帮助您获得:所选值,所选文本以及下拉菜单中的所有值。

  private static void RegisterServices(IKernel kernel)
    {
        kernel.Bind<DidbaanContext>().To<DidbaanContext>();
        kernel.Bind<ICarService>().To<CarService>();
        kernel.Bind<ICarRepository>().To<CarRepository>();

    }     
$(document).ready(function(){
  $("button").click(function(){
      var option = $('option[value="MIPS1"]');
      var select = option.parent();
      var value = $(select).find(":selected").val();
      var optionName = $(select).find(":selected").text();
      var result = "value = "+value+"\noption name = "+optionName+"\nall values = ";
      $(select).each(function(){
          result+=($(this).text()+" ");
	    });
      console.log(result);
    });
});

答案 4 :(得分:0)

我认为不首先将id赋予html元素是一个坏主意,但是,如果您需要这样做,则下面的代码假定页面上只有一个select标记。

let select = document.querySelector('select');
options = select.childNodes.filter((c) => c.tagName==='OPTION')
             .map((o) => o.value);
console.log(options)