Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum and minimum values in a textbox

I have a textbox. Is there a way where the highest value the user can enter is 100 and the lowest is 0?

So if the user types in a number more than 100 then it will automatically 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 is below:

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

Can this be done using JavaScript?

like image 571
BruceyBandit Avatar asked Jan 06 '12 17:01

BruceyBandit


People also ask

How can we set minimum and maximum value in textbox?

The min attribute specifies the minimum value for an <input> element. Tip: Use the min attribute together with the max attribute to create a range of legal values. Note: The max and min attributes works with the following input types: number, range, date, datetime-local, month, time and week.

Which of the following attribute is used specify min and max value for a model field?

Simply use Range DataAnnotation attribute on your model property.


1 Answers

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 min; 
    else if(parseInt(value) > max) 
        return max; 
    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

like image 83
Nikoloff Avatar answered Sep 21 '22 04:09

Nikoloff