我环顾四周,之前没有看到有人问过这个问题。
我有一个选择框,像这样:
<select onchange="change()">
<option value="" selected>Option 1</option>
<option value="30">Option 2</option>
<option value="90">Option 3</option>
</select>
我想添加另一个选项...
<option value="custom">Option 4</option>
...that when chosen (clicked) an alert box will popup asking the user to type in a number (in the case 30 or 90 weren't viable options, as in the values of the option's) to replace the value的选项。
<script>
function change() {
if(value == "custom") {
value = prompt("Please enter a new number:", "60");
}
}
</script>
我想知道最好的方法是使用普通的旧 javascript - 如果必须的话,我会使用 jQuery。
有什么想法吗?一个例子也很好。
最佳答案
看看这段代码。我认为这就是您想要做的:
HTML
<select id="optionvals" onclick="change()">
<option value="" selected>Option 1</option>
<option value="30">Option 2</option>
<option value="90">Option 3</option>
<option value="custom">Option 4</option>
</select>
JS
function change() {
var oItem = document.getElementById('optionvals');
var value = oItem.options[oItem.selectedIndex].value;
if(value == "custom") {
alert("you've clicked b");
value = prompt("Please enter a new number:", "60");
oItem.options[oItem.selectedIndex].value = value;
console.log(oItem.options[oItem.selectedIndex].value)
}
}
What this does is prompt you on the change only if the selected value in the options is custom
.然后在您选择自定义值后,它会将 custom
选项元素的值重写为您刚刚在提示中输入的值。我在分配新值后记录了它,以向您展示它正在工作。
这是一个 fiddle :https://jsfiddle.net/ng7xvy05/
关于javascript - JS : Change select option value on being selected with prompt?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36110153/