I need code that changes input value if its above max or belove min number. For example min is 1 and max 10. If input is set to 15 then it changes to 10 and if its set to 0 then it changes to 1. And it should work without reloading page.
2 Answers
Use the min and max attributes of the number-typed input element:
<input type="number" min="1" max="10" placeholder="Enter a number between 1 and 10" />
The form will prevent the user from entering values outside of the range, without any coding.
If you want your input to support decimals, add the step="any" attribute.
Comments
Use as
Here's a simple function that does what you need:
<script type="text/javascript">
function minmax(value, min, max)
{
if(parseInt(value) < 0 || isNaN(value))
return 1;
else if(parseInt(value) > 10)
return 10;
else return value;
}
</script>
<input type="text" name="textWeight" id="txtWeight" maxlength="5" onkeyup="this.value = minmax(this.value, 0, 10)"/>
If the input is not numeric it replaces is with 1
<input type="number" min="1" max="10"/>should work.