Gustavo Marin
Gustavo Marin

Reputation: 59

How to limit the input within a range of values

I have an input box and it should only allow float values within the range of -90 to 90. Make the Send button unclickable when the value is not within the allowed range. And display a text when trying to click the button saying the input is invalid.

For now I could limit the input using keycode, even though this only allows to enter numbers and one single decimal point and negative sign, it will let you put the sign anywhere. Here's a demo

$('#inputLat').keypress(function(event) {
    var code = (event.keyCode ? event.keyCode : event.which);
    if (!(
            (code >= 48 && code <= 57) //numbers
            || (code >= 45 && code <= 46) //period
        )
        || (code == 46 && $(this).val().indexOf('.') != -1)
				|| (code == 45 && $(this).val().indexOf('-') != -1)
       )
        event.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="inputLat">Latitude</label>
<br>
<input type="text" id="inputLat" placeholder="-90° to +90°">
<br>
<button type="button" id="sendButton">Send</button>

I expect the sign to be at the beginning only.

Upvotes: 0

Views: 122

Answers (2)

jspcal
jspcal

Reputation: 51944

perhaps bind to the input event and perform your numerical validation there:

$('#inputLat').on('input', function() {
    var num = parseFloat($(this).val());

    if (num >= -90 && num <= 90) {
        // Input is valid
        console.log('Valid');
        $('#inputLatLabel').removeClass('error');
        $('#sendButton').prop('disabled', false);
    } else {
        // Input is invalid
        console.log('Invalid');
        $('#inputLatLabel').addClass('error');
        $('#sendButton').prop('disabled', true);
    }
});
.error {color: red;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label id="inputLatLabel" for="inputLat">Latitude</label>
<br>
<input type="text" id="inputLat" placeholder="-90° to +90°">
<br>
<button type="button" id="sendButton" disabled>Send</button>

Upvotes: 0

The Head Rush
The Head Rush

Reputation: 3356

You could user <input type="range">, if you don't mind a slider in browsers that support it. Rolls back to a text input if browser doesn't, and would probably need custom validation.

<div>
  <input type="range" id="start" name="volume"
         min="-90" max="90">
  <label for="volume">Volume</label>
</div>

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/range

Or you could use <input type="number">

<input type="number" min="-90" max="90">

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number

Upvotes: 1

Related Questions