我想在下拉菜单中添加一个选项,如果其中一个选项不适用,用户可以在其中手动输入信息。我做了一个简单的下拉列表, 以颜色为例。最后一个输入是 Other ,但是,如果用户选择该输入,我不知道如何使其可编辑。有任何想法吗?非常感谢您的帮助。
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
<style type="text/css">
table,
td,
th {
margin-left: auto;
margin-right: auto
}
.display {
display: flex;
align-items: center;
justify-content: center;
}
p {
text-align: center;
}
textarea {
display: block;
margin-left: auto;
margin-right: auto;
}
</style>
<body>
<table>
<tr>
<td>
<select name="color" id="z4">
<option value="" disabled selected>Color</option>
<option value="red">Red</option>
<option value="orange">Orange</option>
<option value="yellow">Yellow</option>
<option value="green">Green</option>
<option value="purple">Purple</option>
<option value="white">White</option>
<option value="black">Black</option>
<option value="gray">Gray</option>
<option value="Other">Other</option>
</select>
</td>
</tr>
</table>
<br>
<div class="display">
<button onclick="sentence()"> Submit </button>
</div>
</body>
</html>
答案 0 :(得分:0)
添加一个input
字段,并将事件侦听器附加到select
字段。
如果用户选择选项 Other ,则显示{{1} }字段。当用户点击提交按钮时,请使用此input
字段中的值。
input
// select the necessary elements
var select = document.querySelector('#z4');
var other = document.querySelector('#other');
// use this flag to easily determine, whether the user selected the other option
var isOther = false;
// listen, when the user changes the select field
select.addEventListener('change', function () {
// get the currently selected value of the select field
var value = this.value;
// if the user selected "Other", show the other input field
if (value === 'Other') {
other.style.display = 'inline';
isOther = true;
// otherwise hide the other input field
} else {
other.style.display = 'none';
isOther = false;
}
});
// the function, that will be used upon submitting
function sentence() {
// if the other input field is selected, get its value
if (isOther) {
console.log('other used:', other.value);
} else {
console.log('regular used');
}
}
table,
td,
th {
margin-left: auto;
margin-right: auto
}
.display {
display: flex;
align-items: center;
justify-content: center;
}
p {
text-align: center;
}
textarea {
display: block;
margin-left: auto;
margin-right: auto;
}
#other {
display: none;
}