使用 JavaScript 向文本字段输入添加美元符号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18336896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding a Dollar Sign to a Text Field Input using JavaScript
提问by MMM Bacon
Using JavaScript, I'm looking to automatically put a dollar sign in front of the entered amount in an input field within a form. I'm using the below code, but am not sure what I'm missing:
使用 JavaScript,我希望在表单中的输入字段中自动在输入的金额前放置一个美元符号。我正在使用以下代码,但不确定我错过了什么:
<!DOCTYPE html>
<head>
<title>Example</title>
<script>
var test = document.getElementById("name");
document.write("$"+test.value);
</script>
</head>
<body>
<form action="" method="get">
<input type="text" id="name"/>
</form>
</body>
</html>
Any help is appreciated. Thanks!
任何帮助表示赞赏。谢谢!
回答by Grammin
The best way to do this would be something like:
最好的方法是:
Amount: $<input type="number" id="name" min="0" max="9999" step="0.01"/>
回答by ced-b
This is the way you would add the dollar sign: http://jsfiddle.net/VSuvA/.
这是添加美元符号的方式:http: //jsfiddle.net/VSuvA/。
HTML:
HTML:
<form action="" method="get">
<input type="text" id="name" onblur="handleChange()"/>
</form>
JS:
JS:
function handleChange() {
var myValue = document.getElementById("name").value;
if (myValue.indexOf("$") != 0)
{
myValue = "$" + myValue;
}
document.getElementById("name").value = myValue;
}
You have to listen to an event like onchange
or onblur
and then set the value back. document.write
will not do what you need.
您必须收听像onchange
or 之类的事件onblur
,然后将值设置回原位。document.write
不会做你需要的。