[英]How to save select dropdown menu option in HTML/pure JS?
Let's say I have this code:假设我有这个代码:
<select id = dropdown-list>
<option value = "0"> Yes </option>
<option value = "1"> No </option>
</select>
The user can select yes or no from a dropdown list.用户可以从下拉列表中选择 select 是或否。 How can I use pure JS/HTML to figure out what the user has selected (and is currently showing in the dropdown list box when the list isn't expanded) so I can use that data elsewhere?如何使用纯 JS/HTML 来确定用户选择的内容(当列表未展开时当前显示在下拉列表框中),以便我可以在其他地方使用该数据? The only way I can figure out is if I add an eventListener on each option but I feel there is a better way.我能弄清楚的唯一方法是是否在每个选项上添加一个 eventListener 但我觉得有更好的方法。 I am quite new to JS so I'm not sure.我对JS很陌生,所以我不确定。 Thank you.谢谢你。
You can use onchange
attribute from select
element.您可以使用select
元素中的onchange
属性。
<select id="dropdown-list" onchange="onChange(this.value)">
<option value = "0"> Yes </option>
<option value = "1"> No </option>
</select>
and in JS:在 JS 中:
function onChange(val) {
// `val` is the value
}
You may want to use on change event.您可能想在更改事件上使用。 Since you use each I suppose you are using Jquery.由于您使用每个我想您正在使用 Jquery。 If you have any question just let me know.如果您有任何问题,请告诉我。
$(document).ready(function(){
$('#dropdown-list').on('change',function(){
alert($(this).children('option:selected').val());
})
});
https://jsfiddle.net/u4dz162o/ https://jsfiddle.net/u4dz162o/
Execute a JavaScript function changeResult
when a user changes the selected option of a element:当用户更改元素的选定选项时,执行 JavaScript function changeResult
:
Flow:流动:
changeRegult
using onchange
event listener.我们使用onchange
事件监听器绑定changeRegult
。changeResult
function.当我们更改下拉菜单时,它会调用changeResult
function。dropdown menu
using its id
property.在 function 内部,我们使用其id
属性 select dropdown menu
。document.getElementById("dropdown-list").value
.这里我们要显示 value 属性,所以我们使用document.getElementById("dropdown-list").value
。For more check this link .有关更多信息,请查看此链接。
function changeResult() { var x = document.getElementById("dropdown-list").value; document.getElementById("result").innerHTML = "You selected: " + x; }
<select id = "dropdown-list" onchange="changeResult()"> <option value = "0"> Yes </option> <option value = "1"> No </option> </select> <p id="result"></p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.