Ad

Add Character Function Need To Add 0 Before Decimal Point

- 1 answer

I'm using the following JavaScript to add a decimal into an input field:

function addChar(input, character) {
  if (input.value == null || input.value == "0"){
    input.value = character}
  else{
    input.value += character}
  };

$('#button-dot').click(function() {
  addChar(this.form.display, '.');
  });

with HTML markup:

<INPUT NAME="display" ID="disp" VALUE="0" SIZE="28" MAXLENGTH="25"/>
<button TYPE="button" ID="button-1" VALUE="1">1</button>
<button TYPE="button" ID="button-2" VALUE="2">2</button>
<button TYPE="button" ID="button-3" VALUE="3">3</button>
<button TYPE="button" ID="button-4" VALUE="4">4</button>
<button TYPE="button" ID="button-5" VALUE="5">5</button>
<button TYPE="button" ID="button-6" VALUE="6">6</button>
<button TYPE="button" ID="button-7" VALUE="7">7</button>
<button TYPE="button" ID="button-8" VALUE="8">8</button>
<button TYPE="button" ID="button-9" VALUE="9">9</button>
<button TYPE="button" ID="button-0" VALUE="0">0</button>
<button TYPE="button" ID="button-dot" VALUE=".">.</button>

When the user presses the the #button-dot key prior to any number key, the decimal appears with no zero to the left of it and I would like for that to be the case. So is there a way to alter this code such that when the user inputs the decimal point as the first key, a zero will appear to the left of the decimal?

Ad

Answer

Try this handler:

$('#button-dot').click(function(){
    var txt = disp.val().replace(/\./g, '');
    if(!txt)
        txt = '0';
    txt += '.';
    disp.val(txt);
});

$(function() {

  var disp = $('#disp');

  //all buttons except for last button `dot`
  $('[id^=button-]').slice(0, -1).click(function() {
    var txt = disp.val();
    if('0' === txt) { //modified condition
      txt = '';
    }
    disp.val(txt + this.value);
  });

  $('#button-dot').click(function() {
    var txt = disp.val().replace(/\./g, ''); //replace all previous dots
    if (!txt)
      txt = '0';
    disp.val(txt + '.');
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<INPUT NAME="display" ID="disp" VALUE="0" SIZE="28" MAXLENGTH="25" />
<button TYPE="button" ID="button-1" VALUE="1">1</button>
<button TYPE="button" ID="button-2" VALUE="2">2</button>
<button TYPE="button" ID="button-3" VALUE="3">3</button>
<button TYPE="button" ID="button-4" VALUE="4">4</button>
<button TYPE="button" ID="button-5" VALUE="5">5</button>
<button TYPE="button" ID="button-6" VALUE="6">6</button>
<button TYPE="button" ID="button-7" VALUE="7">7</button>
<button TYPE="button" ID="button-8" VALUE="8">8</button>
<button TYPE="button" ID="button-9" VALUE="9">9</button>
<button TYPE="button" ID="button-0" VALUE="0">0</button>
<button TYPE="button" ID="button-dot" VALUE=".">.</button>

Ad
source: stackoverflow.com
Ad