如何将下拉列表中的一个值附加到输入框的末尾?特此附上我的代码。我想在收入输入框的末尾附加货币符号[在下拉列表中选择哪个]。
<html>
<head>
<meta charset="UTF-8">
<title> Stack query</title>
<style>
table{
border: 1px solid black;
height:20%;
width:20%;
margin: 5%;
}
table tr td label, table tr td input,table tr td select {
width:100%;
}
</style>
</head>
<body>
<div>
<table>
<tr>
<td><label for="Currency">Currency</label></td>
<td>
<select name="currency" id="currency">
<option value="Select" selected disabled="disabled">Select Currency</option>
<option value="Dollar">$ USD</option>
<option value="Pound">£ GBP</option>
<option value="Euro">€ EUR</option>
<option value="Yen">¥ YEN</option>
</select>
</td>
</tr>
<tr>
<td><label for="Revenue">Revenue</label></td>
<td><input id="Revenue" type="text" required></td>
</tr>
</table>
</div>
</body>
</html>
您可以使用 <span>
标记以显示货币符号,如下所示:
$('#currency').on('change', function() {
$('#symbol').text(this.options[this.selectedIndex].innerText.charAt(0));
// or the jQuery version
//$('#symbol').text($(this).find('option:selected').text().charAt(0));
});
table {
border: 1px solid black;
height: 20%;
width: 40%;
margin: 5%;
}
table tr td label,
table tr td input,
table tr td select {
width: 80%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<table>
<tr>
<td>
<label for="Currency">Currency</label>
</td>
<td>
<select name="currency" id="currency">
<option value="Select" selected disabled="disabled">Select Currency</option>
<option value="Dollar">$ USD</option>
<option value="Pound">£ GBP</option>
<option value="Euro">€ EUR</option>
<option value="Yen">¥ YEN</option>
</select>
</td>
</tr>
<tr>
<td>
<label for="Revenue">Revenue</label>
</td>
<td>
<input id="Revenue" type="text" required>
<span id="symbol"></span>
</td>
</tr>
</table>
</div>
要更新文本框值本身,请尝试类似的操作:
$('#currency').on('change', function() {
var selected;
var symbols = $(this.options).map(function(option) {
if (this.selected)
selected = this.innerText.charAt(0);
return this.innerText.charAt(0);
}).get();
$('#Revenue').val(function(i, val) {
if (!val) return
return symbols.indexOf(val.slice(-1)) >= 0 ?
val.slice(0, -1) + selected : val + selected;
});
});
table {
border: 1px solid black;
height: 20%;
width: 40%;
margin: 5%;
}
table tr td label,
table tr td input,
table tr td select {
width: 80%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<table>
<tr>
<td>
<label for="Currency">Currency</label>
</td>
<td>
<select name="currency" id="currency">
<option value="Select" selected disabled="disabled">Select Currency</option>
<option value="Dollar">$ USD</option>
<option value="Pound">£ GBP</option>
<option value="Euro">€ EUR</option>
<option value="Yen">¥ YEN</option>
</select>
</td>
</tr>
<tr>
<td>
<label for="Revenue">Revenue</label>
</td>
<td>
<input id="Revenue" type="text" required>
<span id="symbol"></span>
</td>
</tr>
</table>
</div>
我是一名优秀的程序员,十分优秀!