[javascript] 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?

This question is related to javascript html

The answer is


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


Yes it can! You might consider first to set the value of maxlength to 3 and then write an event handler for the keyup-event.

The function can evaluate the user input using regex or parseInt to validate the user input and set it to any desired value, if the input is incorrect.


Its quite simple dear you can use range validator

<asp:TextBox ID="TextBox2" runat="server" TextMode="Number"></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server"   
    ControlToValidate="TextBox2"   
    ErrorMessage="Invalid number. Please enter the number between 0 to 20."   
    MaximumValue="20" MinimumValue="0" Type="Integer"></asp:RangeValidator>   
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"   
    ControlToValidate="TextBox2" ErrorMessage="This is required field, can not be blank."></asp:RequiredFieldValidator>

otherwise you can use javascript

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

Set Attributes in CodeBehind

textWeight.Attributes.Add("minimum", minValue.ToString());
textWeight.Attributes.Add("maximum", maxValue.ToString());

Result:

<input type="text" minimum="0" maximum="100" id="textWeight" value="2" name="textWeight">

By jQuery

    jQuery(document).ready(function () {

        var textWeight = $("input[type='text']#textWeight");

        textWeight.change(function () {

              var min = textWeight.attr("minimum");

              var max= textWeight.attr("maximum");

              var value = textWeight.val();

              if(val < min || val > max)
              {
                    alert("Your Message");

                    textWeight.val(min);
              }

        });
    });

If you are OK with HTML5 it can be accomplished without any JavaScript code at all...

<input type="number" name="textWeight" id="txtWeight" max="5" min="0" />

Otherwise, something like...

var input = document.getElementById('txtWeight');

input.addEventListener('change', function(e) {
    var num = parseInt(this.value, 10),
        min = 0,
        max = 100;

    if (isNaN(num)) {
        this.value = "";
        return;
    }

    this.value = Math.max(num, min);
    this.value = Math.min(num, max);
});

This will only reset the values when the input looses focus, and clears out any input that can't be parsed as an integer...

OBLIGATORY WARNING

You should always perform adequate server-side validation on inputs, regardless of client-side validation.


https://jsfiddle.net/co1z0qg0/141/

<input type="text">
<script>
$('input').on('keyup', function() {
    var val = parseInt($(this).val()),
        max = 100;

    val = isNaN(val) ? 0 : Math.max(Math.min(val, max), 0);
    $(this).val(val);
});
</script>

or better

https://jsfiddle.net/co1z0qg0/142/

<input type="number" max="100">
<script>
$(function() {
    $('input[type="number"]').on('keyup', function() {
        var el = $(this),
            val = Math.max((0, el.val())),
            max = parseInt(el.attr('max'));

        el.val(isNaN(max) ? val : Math.min(max, val));
  });
});
</script>
<style>
input[type="number"]::-webkit-outer-spin-button,
input[type="number"]::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}
input[type="number"] {
    -moz-appearance: textfield;
}
</style>

I would typically do something like this (onblur), but it could be attached to any of the events:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<script type="text/javascript">
function CheckNo(sender){
    if(!isNaN(sender.value)){
        if(sender.value > 100 )
            sender.value = 100;
        if(sender.value < 0 )
            sender.value = 0;
    }else{
          sender.value = 0;
    }
}

</script>
</head>

<body>
<input type="text" onblur="CheckNo(this)" />
</body>
</html>

It depends on the kind of numbers and what you will allow. Handling numbers with decimals is more difficult than simple integers. Handling situations where multiple cultures are allowed is more complicated again.

The basics are these:

  • Handle the "keypress" event for the text box. When a character which is not allowed has been pressed, cancel further processing of the event so the browser doesn't add it to the textbox.
  • While handling "keypress", it is often useful to simple create the potential new string based on the key that was pressed. If the string is a valid number, allow the kepress. Otherwise, toss the keypress. This can greatly simplify some of the work.
  • Potentially handle the "keydown" event if you're concerned with keys that "keypress" doesn't handle.

function

getValue(input){
        var value = input.value ? parseInt(input.value) : 0;
        let min = input.min;
        let max = input.max;
        if(value < min) 
            return parseInt(min); 
        else if(value > max) 
            return parseInt(max);
        else return value;
    }

Usages

changeDotColor = (event) => {
        let value = this.getValue(event.target) //value will be always number
        console.log(value)
        console.log(typeof value)
}

If you're not using HTML5 this is a pretty basic JavaScript form validation.

Side note - I'd change the value to 0 on the blur event instead of keyup (as a user I think changing the text as I'm typing would be annoying to no end).