Lesley Peters Lesley Peters - 1 year ago 87
HTML Question

Only numbers in textbox not greater than account balance

I am working on a bitcoin website, and every user has an account balance that looks like this: 1.26584000 or 0.00032568. Note that there are always 8 digits after the decimal.

Now I want users to fill in a textbox with an amount of bitcoins, but this textbox may only contain numbers, and if the number is greater then the account balance it should automatically replace with their maximum available balance.

The account balance is stored in a php variable ($balance) as a string like this:

$balance = number_format((float)$activeUser['balance'], 8, '.', '');

The current textbox I have looks like this:

<input class="form-control col-md-10 input-lg" type="text" value="0.00000000" />

I already found some solutions with Javascript but I couldn't get the result how I wanted it to be.

Answer Source

Simply compare two values and find it's minimum:

$(document).ready(function () {
  var accountMax = (Math.random() * 10).toPrecision(8);
  console.log('Account balance: '+accountMax);
  $('#value-input').change(function () {
    var inputed = parseFloat($(this).val()).toPrecision(8);
    $(this).val(Math.max(0, Math.min(inputed, accountMax)).toPrecision(8));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
BitCoinHacker3000: <input type="text" value="0.00000000" id="value-input"/>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download