我是JavaScript和jQuery的新手。我想显示一个combobox-A,这是一个HTML <选择>与其选择的id和内容在onChange()的其他地方。
如何通过其选择id完整的组合框,以及如何通过onChange事件的其他参数?
我是JavaScript和jQuery的新手。我想显示一个combobox-A,这是一个HTML <选择>与其选择的id和内容在onChange()的其他地方。
如何通过其选择id完整的组合框,以及如何通过onChange事件的其他参数?
当前回答
我发现@Piyush的回答很有帮助,只是补充一下,如果您以编程方式创建一个选择,那么有一个重要的方法来获得这种行为,可能不明显。假设你有一个函数,你创建了一个新的select:
var changeitem = function (sel) {
console.log(sel.selectedIndex);
}
var newSelect = document.createElement('select');
newSelect.id = 'newselect';
正常的行为可能是说
newSelect.onchange = changeitem;
但是这并不允许你指定传入的参数,所以你可以这样做:
newSelect.setAttribute('onchange', 'changeitem(this)');
你可以设置参数。如果采用第一种方法,那么onchange函数的参数将依赖于浏览器。第二种方法似乎在跨浏览器中工作得很好。
其他回答
如果有人正在寻找一个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);
函数setMyValue(v) { console.log (v); } <选择onchange = " setMyValue (this.value)" > <选项值= " " > 1 > < /选项 <选项值= " b " > 2 > < /选项 <选项值= " c " > 3 < /选项> < /选择>
Html模板:
<select class="staff-select">
<option value="">All</option>
<option value="196">Ivan</option>
<option value="195">Jon</option>
</select>
Js代码:
const $staffSelect = document.querySelector('.staff-select')
$staffSelect.onchange = function () {
console.log(this.value)
}
简单:
函数检索(){ 警报(. getelementbyid (SMS_recipient) .options [. 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>
输出: Klaus或Andrew取决于selectedIndex是什么。如果你想要的是值,只需将.text替换为value。然而,如果它只是你想要的值(而不是选项中的文本),那么使用document.getElementById(' sms_receiver ').value
//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);
}