Question

This is an extension to this thread.


My situation:

  • I need a user to enter a decimal value (ie 0.05) and show a simple calculation on the fly as the user types (or pastes). The example shown works for whole numbers but not when a decimal is entered into the input field.

  • I need to display the result in multiple places. I assumed I could just update getElementById to getElementByClass but that didn't work.

My Code:

<input type="text" name="capname" id="numberField" value="0.07" maxlength="5" />
<span name="mpd" id="mpdresult" class="mpdresult" ></span>  
<span class="mpdresult" ></span> (second display)

<script>
window.onload = function() {
   var base = 500;
   var numberField = document.getElementById('numberField');
   numberField.onkeyup = numberField.onpaste = function() {
      if(this.value.length == 0) {
         document.getElementById('mpdresult').innerHTML = '';
         return;
      }
      var number = parseInt(this.value);
      if(isNaN(number)) return;
      document.getElementById('mpdresult').innerHTML = number * base;
   };
   numberField.onkeyup(); //could just as easily have been onpaste();
};
</script>
Was it helpful?

Solution

please use var number = parseFloat(this.value);

instead of var number = parseInt(this.value);

OTHER TIPS

use ParseFolat for Decimal Numbers

document.write(parseFloat("10.33") + "<br>");

ParseFloatSample

  1. Use parseFloat instead of parseInt. http://jsfiddle.net/janCY/

  2. there is no such function getElementByClass. There is getElementsByClassName, it returns array with elements. But why don't use JQuery?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top