可以更改A< select>下拉菜单值通过JavaScript
我的网站上有一个选择的下拉列表,当我出于某种原因点击取消按钮时,该值不会更改为占位符。我试图在我的JavaScript代码中替换其值。不幸的是,Stackoverflow无法正确运行我的代码,但是点击事件在我的网站上工作。它只是清除了选择菜单,而不是说“选择时区”。关于我可能做错什么的建议吗?
const cancel = document.getElementById("cancel");
let zone = document.getElementById("timezone");
var zoneVal = localStorage.getItem("timezone");
cancel.addEventListener('click', () => {
localStorage.clear();
zone.value = 'Select Timezone';
});
<select class="form-field" id="timezone">
<option disabled selected>Select a Timezone</option>
<option>Eastern</option>
<option>Western</option>
<option>PDT</option>
<option>EST</option>
</select>
<button class="button-disabled" id="cancel">Cancel</button>
I have a select dropdown on my website and when I hit the cancel button for some reason the value does not change back to it's placeholder. I attempted to replace the .value of it in my javascript code. Unfortunately stackoverflow isn't running my code properly but the click event works on my website. It just clears the select menu and is blank instead of saying "Select Timezone". Any suggestions of what I could be doing wrong?
const cancel = document.getElementById("cancel");
let zone = document.getElementById("timezone");
var zoneVal = localStorage.getItem("timezone");
cancel.addEventListener('click', () => {
localStorage.clear();
zone.value = 'Select Timezone';
});
<select class="form-field" id="timezone">
<option disabled selected>Select a Timezone</option>
<option>Eastern</option>
<option>Western</option>
<option>PDT</option>
<option>EST</option>
</select>
<button class="button-disabled" id="cancel">Cancel</button>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于测试,我禁用您的本地存储,因为它在片段中不起作用。
您可以只使用 element.selectedIndex = 0; 在选择中选择第一个选项
For testing, I disabled your localstorage since it doesn't work in the snippets.
You can just use element.selectedIndex = 0; to select the first option in a select