Question

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 - http://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>
Was it helpful?

Solution

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.

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