How to set min and max on an input type accepting floating value?

Viewed 970

There are plenty of examples showing how to set min and max with integers. I need to ensure the range of values can even be float. Below is how I'm setting the attributes value and max for the input type refund_amount. The problem here is that one can enter a value higher than max value set with Jquery.

window.onload = function() {
    var src = document.getElementById("grand_total");
    var dst = document.getElementById("refund_amount");
    if (dst != "") {
        dst.setAttribute("value", src.textContent);
        dst.setAttribute("max", src.textContent);       
    }
};

HTML:

<tr>
  <td align="right" colspan="3">Enter Refund Amount</td>
  <td align="left" colspan="4"><input type="text" size="11" id="refund_amount" 
                 name="refund_amount" value='' min="" max="" required/></td>
</tr>

How do I ensure it never allows higher value than what max attribute holds?

1 Answers

The min and max attributes only work on type="number" inputs. It's also worth noting that they are not reliable as a means of validation, as they do not prevent the user from typing in a number outside the bounds of the min/max settings.

To work around that you can manually validate the value and correct it to be within bounds by using a change event and the Math.min() and Math.max() functions. Try this:

window.addEventListener('load', function() {
  var src = document.getElementById("grand_total");
  var dst = document.getElementById("refund_amount");

  if (dst) {
    dst.value = dst.max = src.textContent;
  }
});

document.querySelectorAll('input[type="number"]').forEach(input => {
  input.addEventListener('change', e => {
    let el = e.target;
    el.value = Math.min(Math.max(el.value, el.min), el.max);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>Grand total</td>
    <td id="grand_total">25.68</td>
  </tr>
  <tr>
    <td align="right" colspan="3">Enter Refund Amount</td>
    <td align="left" colspan="4">
      <input type="number" step="1" min="11.11" id="refund_amount" name="refund_amount" value="" required />
    </td>
  </tr>
</table>

Related