2

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!

MMM Bacon
  • 71
  • 2
  • 2
  • 12
  • Do you want the dollar sign to be added there after the user finishes typing? What if there's already a dollar sign there? – rink.attendant.6 Aug 20 '13 at 13:56
  • 1
    I suggest you start by reading the [MDN JavaScript Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Getting_Started) ... – Manse Aug 20 '13 at 13:57
  • I'd like to have the dollar sign there as soon as a user places their cursor into the input field. – MMM Bacon Aug 20 '13 at 13:59
  • 2
    http://stackoverflow.com/questions/2218434/fix-a-character-to-text-input-box-using-javascript-jquery – Joban Aug 20 '13 at 13:59
  • Take a look at this question and see if it works http://stackoverflow.com/questions/7609130/set-the-value-of-a-input-field-with-javascript – Felipe Pereira Aug 20 '13 at 14:00
  • Based on a good guess of what your current skill level in JS is, you'll save yourself a lot of work if you just put the $ outside the input box. – JJJ Aug 20 '13 at 14:00
  • var test = document.getElementById("name"); test.value = "$" – Travis Aug 20 '13 at 14:01

2 Answers2

4

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.

ced-b
  • 3,957
  • 1
  • 27
  • 39
3

The best way to do this would be something like:

Amount: $<input type="number" id="name" min="0" max="9999" step="0.01"/>
Grammin
  • 11,808
  • 22
  • 80
  • 138