0

I have the following code which does exactly what I want - it keeps the range slider consistent with the number field, and doesn't allow text field values above the min or max. It also doesn't use jquery which is great.

The problem however is that when I try to enter a custom number that may begin with a number lower than the min value, it will automatically replace it before I have a chance to enter a larger number. Eg: if min is 800 and I want to enter 1600, then I can't do this easily since pressing "1" in the text box will immediately replace it with 800.

Here is the code:

      <script type="text/javascript">
        function minmax(value, min, max)
        {
            if(parseInt(value) > max)
                return max;
            else if (parseInt(value) < min)
                return min;
            else return value;
        }
    </script>
    <form>
        <input type="range" name="amountRange" id ="amountRange" min="<?php echo  $minRaise ?>" max="<?php echo $maxRaise ?>"
               value="<?php echo  $minRaise ?>" oninput="this.form.amountInput.value=this.value" />
        <input type="number" name="amountInput" min="<?php  echo $minRaise ?>" max="<?php echo $maxRaise ?>" value="<?php  echo $minRaise ?>"
               onkeyup="this.value = minmax(this.value, <?php  echo $minRaise ?>, <?php echo $maxRaise ?>)" oninput="this.form.amountRange.value=this.value" />
    </form>

I thought about inserting a sleep function within the min check part of the faction using the JS sleep example found here: What is the JavaScript version of sleep()? . However unfortunately this resulted in a lot of regex and other errors in the console, leading me to believe there is a more elegant solution.

Any ideas? It would be a shame if I had to butcher the entire code or use jQuery just for such a seemingly simple modification. Since this belongs to a php file loaded from an external jQuery call on another page, I'd rather not use jQuery here.

user4779
  • 645
  • 5
  • 14
  • 1
    You could use a debounce to only call the `minmax` function if no input is detected for a variable amount of time (500ms for example) or you could change the call to `minmax` to `onchange` instead of `onkeyup`. Both of those would require you to remove the `min` and `max` attributes from `amountInput` though. – mrogers Jun 14 '17 at 20:16
  • 1
    try `onchange` rather than `oninput` – Will Jun 14 '17 at 20:42
  • Thanks for the suggestions. I changed onkeyup to onchange. This seems to work without removing the min or max, any idea with this is? Will there be a hidden bug? – user4779 Jun 15 '17 at 04:43

0 Answers0