BruceyBandit BruceyBandit - 1 month ago 19
HTML Question

maximum and minimum values in a textbox

I have a textbox and what I want to know is that is there a way where the highest value the user can enter is 100 and the lowset is 0?

So if user types in a number more than 100 then then it will automatcially change the value to 100 using a keyup() function and if user types in a number less than 0 it will display as 0?

My textbox below:

<input type="text" name="textWeight" id="txtWeight" maxlength="5"/>%</td>


Can this be done using javascript?

Answer

Here's a simple function that does what you need:

<script type="text/javascript">
function minmax(value, min, max) 
{
    if(parseInt(value) < min || isNaN(parseInt(value))) 
        return 0; 
    else if(parseInt(value) > max) 
        return 100; 
    else return value;
}
</script>
<input type="text" name="textWeight" id="txtWeight" maxlength="5" onkeyup="this.value = minmax(this.value, 0, 100)"/>

If the input is not numeric it replaces it with a zero

Comments