如何在HTML select的onChange事件中传递参数

265

我是JavaScript和jQuery的初学者。我想在onChange()事件中展示一个下拉框A,这个下拉框是一个HTML <select>元素,需要同时传递它的选中id和内容到另一个地方。

我该如何传递整个下拉框及其选择的id,以及如何在触发onChange事件时传递其他参数?


6
请问您能否提供一些代码? - KJYe.Name
17个回答

2

如果有人在不下载额外依赖项的情况下寻找React解决方案,则可以编写以下内容:

<select onChange={this.changed(this)}>
   <option value="Apple">Apple</option>
   <option value="Android">Android</option>                
</select>

changed(){
  return e => {
    console.log(e.target.value)
  }
}

请确保在构造函数中绑定changed()函数,如下所示:

this.changed = this.changed.bind(this);

1

function setMyValue(v) {
  console.log(v);
}
<select onchange="setMyValue(this.value)">
  <option value="a">1</option>
  <option value="b">2</option>
  <option value="c">3</option>
</select>


1

我写了这段代码只是为了解释


0

这对我有用 onchange = setLocation($(this).val())

在这里。

    @Html.DropDownList("Demo", 
new SelectList(ViewBag.locs, "Value", "Text"), 
new { Class = "ddlStyle", onchange = "setLocation($(this).val())" });

0
 //html code
   <select onchange="get(this)">
      <option value="a">1</option>
      <option value="b">2</option>
      <option value="c">3</option>
    </select>

//javscript code
   function get(select) {
      let value = select.value;  
      console.log(value);
    }
    

请编辑您的答案,并添加一些文本说明为什么以及如何工作,以及它与其他答案的区别。 - ahuemmer

0

简单地说:

function retrieve(){
alert(document.getElementById('SMS_recipient').options[document.getElementById('SMS_recipient').selectedIndex].text);
}

function retrieve_other() {
  alert(myForm.SMS_recipient.options[document.getElementById('SMS_recipient').selectedIndex].text);
}

function retrieve() {  alert(document.getElementById('SMS_recipient').options[document.getElementById('SMS_recipient').selectedIndex].text);
}
<HTML>
<BODY>
  <p>RETRIEVING TEXT IN OPTION OF SELECT </p>
  <form name="myForm" action="">
    <P>Select:
      <select id="SMS_recipient">
        <options value='+15121234567'>Andrew</option>
          <options value='+15121234568'>Klaus</option>
      </select>
    </p>
    <p>
      <!-- Note: Despite the script engine complaining about it the code works!-->
      <input type="button" onclick="retrieve()" value="Try it" />
      <input type="button" onclick="retrieve_other()" value="Try Form" />
    </p>
  </form>
</HTML>
</BODY>

输出: 根据selectedIndex是Klaus或者Andrew。如果你需要的是值,只需将“.text”替换为“value”。但是,如果你只需要值(而不是选项中的文本),则使用document.getElementById('SMS_recipient').value


0

我认为现在附加事件处理程序的首选方式(而不是使用 onchange 属性)是

document.querySelector('whatever').addEventListener('change', (event) => {
   const theValue = event.target.value;
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接