1

How would I use javascript to create an input field where each time the user clicks on a button in the image below, the value replaces the last zero.

Screenshot - https://i.stack.imgur.com/rikcT.png

Example:

User Clicks 1 - Value of textbox: 0.01

User Then Clicks 5 - Value of textbox: 0.15

User Then Cliks 7 - Value of textbox: 1.57

etc.

Currently, if the textbox has 0.00 and the user clicks 1, the new input is 0.001.

I am not sure what this is called to research a reliable way to accomplish it.

Edit: The current code is as follows:

<form name="Tender"
  <input name="Amount" type="text"/>
</form>

<a href="#" OnClick="Tender.Amount.value += '1'" class="btn btn-primary btn-large">1</a>
<a href="#" OnClick="Tender.Amount.value += '2'" class="btn btn-primary btn-large">2</a>
<a href="#" OnClick="Tender.Amount.value += '3'" class="btn btn-primary btn-large">3</a>
user3377041
  • 103
  • 1
  • 1
  • 4
  • Show us your code for `if the textbox has 0.00 and the user clicks 1, the new input is 0.001`. 0.00 + 0.01 should work... Also you might want to look at http://stackoverflow.com/questions/6134039/format-number-to-always-show-2-decimal-places – nickdos Mar 04 '14 at 00:48

1 Answers1

1

This seems to work:

var num = 0.01
var add = (num.toFixed(2) + 5) * 10

The basic idea is that it takes the number, tells it to be added to the 1000ths place (so in this case, after the 1), adds the new number in the 1000ths place, then multiplies by 10 to account for the decimal shift.

You could then make a function:

function add(base, add){
    return (base.toFixed(2) + add) * 10
}

Which isn't super pretty, but:

add(add(0.01, 5), 7);

Or:

var base = 0.01,
    numbers = [5, 7];
for (var i = 0; i < numbers.length; i++){
    base = add(base, numbers[i]);
}
alert(base);

Would output 1.57.

Here's an example.

Charlie
  • 11,380
  • 19
  • 83
  • 138
  • How would I integrate that into my current code? I do not understand how to integrate it. (Still learning basic Javascript) – user3377041 Mar 04 '14 at 01:12
  • @user3377041 Something like this: http://jsfiddle.net/charlescarver/pN5pK/. Although I quickly whipped that up, you'll have to test it to make sure it works perfectly – Charlie Mar 04 '14 at 01:24