Reputation: 71
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:
<!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!
Upvotes: 2
Views: 19891
Reputation: 4065
This is the way you would add the dollar sign: http://jsfiddle.net/VSuvA/.
HTML:
<form action="" method="get">
<input type="text" id="name" onblur="handleChange()"/>
</form>
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.
Upvotes: 4
Reputation: 12205
The best way to do this would be something like:
Amount: $<input type="number" id="name" min="0" max="9999" step="0.01"/>
Upvotes: 3