Only-numerics in Input - javascript

I currently have a snippet that only allows numbers to be typed into an input:
$('input').bind('keypress', function(event) {
var charCode = event.which;
var keyChar = String.fromCharCode(charCode);
return /[0-9]/.test(keyChar);
});
jsFiddle: http://jsfiddle.net/wgsPr/
How can I adjust this to prevent typing in numbers greater than 500?
For example, if a user types 50, then types a 1 after, it won't display the 1. However if the user types a 0 after, it will display 500. And the same goes for if a user tries to type 968 it will not show the 8, it will only show 96.
Hopefully this makes sense.

The line would be
return /\d/.test(keyChar) && parseInt(this.value+keyChar, 10) <= 500;
(Demo)
However, I still suggest not to hook on and preventDefault of keypress events - go for keyup and change events and show error messages if the input's value is invalid. Or use a HTML5 <input type="number" /> with min and max attributes.

You really should not use such methods. This works far better:
<input type="number" min="0" max="500" />
However, if you insist, take your existing code and replace the return line with:
return /\d/.test(keyChar) && this.value <= 500;

if ($(this).val() > 500) {
$(this).val($(this).val().substr(0, $(this).val().length - 1));
return false;
}
I went ahead and attempted to solve this myself, which works. Basically, it checks the value and remove the last character in the case that it makes the entire input value larger than 500. Please let me know if anything should be modified.

Related

Enter less than or equal value using Javascript

I am trying to given alert to the user, if user enter more than input variable value.
problem statement:
Max_ava_water = 300
if user enter a 6 also it is showing 'Enter less or Equal values'.
var Max_ava_water = 300
$('#input_rd').keyup(function() {
if ($(this).val() > Max_ava_water) {
console.log("Enter less or Equal values")
$(this).val('');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="value" id="input_rd" />
You're checking on every keyup event, which is too soon — the user could be trying to type 600, which starts with 6, which is less than 100. (Sorry, that comment was when I'd misread your > as <. But the basic idea still applies.)
Instead, check when the field loses focus (blur) or when they try to confirm the value in some other way.
I'd strongly suggest not clearing the field when the value is too low. Instead, let them edit the value (maybe they just missed out a 0 at the end).
const Max_ava_water = 300;
// Using `blur` event
$('#input_rd').on("blur", function() {
// Explicit conversion
const value = this.value ? parseInt(this.value, 10) : NaN;
// Note that `NaN` is never `>` anything
if (value > Max_ava_water) {
console.log("Enter less or Equal values")
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="input_rd" />
Also note that type="value" is invalid for input fields. You could use type="number" as I did above to trigger the browser's standard handling for number fields, perhaps with min and max to do range checking.
Side note: val returns a string (or undefined if you call it on an empty jQuery set, but you aren't). Your expression relies on > to implicitly convert that to a number. > does do that, but often it's better to do the conversion intentionally, not least because the rules for implicit conversion might not be the rules you want to apply ("" converts to 0, for instance). My answer here describes your various options and their pros and cons.

How to check for the multiple dots and stop to enter multiple dot using javascript?

I am having a input type text.
<input type="text" class="checkForDot" />
What i am trying to do is, when a user enters numbers into the box then find for the "." in the field, if it contains more then one ".", then prevent it to enter another "." in the text field.
my jquery code is:
$(".checkForDot").on("keyup", function (event) {
CheckForDot($(this).val());
});
function CheckForDot(value) {
if (value != null || value != '') {
var str = value.toString();
if (str.indexOf('.', str.indexOf('.') + 1) != -1) {
console.log("ok");
}
}
}
It is working fine, if two "." enters into the text box, but how to prevent to enter multiple "." in the text field?
If any other approach better than this please tell.
$(document).ready(function() {
var original='';
$('.checkForDot').on('input', function() {
if ($(this).val().replace(/[^.]/g, "").length > 1){
$(this).val(original);
}else{
original = $(this).val();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' class='checkForDot' />
Try to use this regex to find how many dots you got in string.
If you are looking to make a field that only allows for numbers, you should consider using an input of type="number" as they will only allow for valid number characters to by added to its value. In some cases, it might even bring a different visual keyboard to ease of filling, wich is better for accessibility and UX. The number input field will, by default allow for mutliple dots, wich is annoying and is a bit harder to prevent than in a text field so it's a case of figuring wether accessibility and your UX is more important than adding a few extra lines of Javascript.
A lot of people will tell you that it is bad practice to limit keyboard actions, and they are right. when you do a preventDefault() on everything but numbers and ".", you disable tabing through form fields, the browser alt menu, any ctrl shortcuts, anything that happens within the browser.
This solution is simple and will only allow one dot in the number field. It doesn't prevent from clicking back in the number and adding numbers before the ".". It doesn't prevent from executing browser keyboard shortcuts like refresh, copy and pasting, as long as the pasted value is a valid number. It will allow to add "." withing the body of the number.
The only behavior that can't be prevented is if the user press the dot key at the end of the input repeatedly, the dot will blink on and off. This happens because of the way the number field handles its value. Wen the user types a dot at the end of a number like "13.", javascript can only retreive "13" when looking at its value as long as no decimal number have been placed. If the user typed a dot again, the value of "13.." would not be a valid number and therefore javascript woudl retreive "". This ensure you eighter get a valid number or nothing at all. In my solution, if a value returns "" without the press of backspace, delete or cut, it gets rolled back to the last valid value, wich in my example was "13", obtained from the typed value "13.". Preventing this behavior seems practically impossible and isn't a deal breaker as you get ensured your field value is always a valid, single dot number.
let lastValidInputValue;
let selectedDot = false;
const onKeypress = (e) => {
if (e.key === "." && e.target.value.indexOf(".") !== -1 && !selectedDot) e.preventDefault();
selectedDot = false;
};
const onInput = (e) => {
if (e.target.value !== "") {
lastValidInputValue = e.target.value;
} else if (e.inputType.match(/delete/g)) {
lastValidInputValue = "";
} else {
e.target.value = lastValidInputValue;
}
};
const onSelect = (e) => {
selectedDot = (window.getSelection().toString().indexOf(".") > -1)? true : false;
}
<input type="number" id="myNumber" name="myNumber" step="any" onkeypress="onKeypress(event)" oninput="onInput(event)" onselect="onSelect(event)">
You can find very detailed comments and extra bits in this Codepen

limiting input field (type=number) to 1 to 20

I have an input field:
<input id="thing" type='number' placeholder='Up to 20 tickets' min='1' max='20' name='tickets'>
And despite the fact that I've listed min and max numbers, it still accepts typing random letters into the field, and such.
I'd like to only allow numbers 1 to 20 to appear in the field upon user input of any kind. How might I do that?
'input' DOM event?
some HTML form magic?
Update Haaa, okay, so dynamically created form inputs don't function like normal inputs. The value fields aren't hooked up to user actions.
Never trust user's input. Limiting values in html input is only for user's convenience. Even if you somehow limited user's ability to change input value directly, he could still press f12 (in Chrome), and manually change values to whatever he wants.
That being said, your code works just fine, and does what you want it to do- it limits user to input just numbers, between 1 and 20. Before doing anything with this data though, you have to validate it on the server, so server will make sure if it's really a number, and it's really between 1 and 20, because as I said- there's no way to prevent user from entering literally anything he wants into inputs.
Using Chrome
document.querySelector( "input" ).addEventListener( "input", function( evt ) {
var v = evt.target.value;
if ( v ) {
console.log( v ); // Only outputs numbers
}
}, false );
<input type="number" value="1" min="1" max="20" name="foo" placeholder="bar">
Behaviour is as expected; nothing but numbers 1-20 are output.
You can use Plain Javascript.
<script>
function handleChange(input) {
if ((input.value < 0) && ((input.value > 20))
return false;
}
</script>
HTMl code
<input type="number" onchange="handleChange(this);" />
Or you can use this
<input type="number" onKeyPress="if(this.value.length>20) return false;" />
I ended up doing this:
var temp = ''
input.addEventListener('input', function (event) {
if (this.value == '') return
if (this.value < 1 || this.value > 20 || this.value.match(/\D/)) return this.value = temp
temp = this.value
}, false)
The input event is the most broad. It captures copy pastes, and all other manner of changing field values.
The check for empty string is important, because if some one has typed 15, and changes their mind, and wants to type 20, they'll need to backspace twice, before typing the 2 and the 0. So, the state of empty is valid.
Anytime the function runs it stores the new value in a temp var, and we apply that immediately if we get input we don't like, because preventDefault() doesn't work with the input event.

Phone number validation using onblur seems to get in a loop

I am using the onblur attribute to call a Javascript phone number validation function. However, if the format of the number is invalid, after displaying an error message using alert(), when I click on the OK button the message is repeated immediately instead of focus being returned to the phone number field to allow me to correct the format. It's impossible to get out of the loop.
This is the code for it:
function validPhone(phoneNum)
// check for valid phone numbers in the format 999-999-9999
{
var strPhone = phoneNum.value;
var rePhone = /\d{3}-\d{3}-\d{4}/;
var blnResult = true;
if (strPhone.length !== 0 && (strPhone.length !== 12 || strPhone.match(rePhone) == null)) {
blnResult = false;
phoneNum.select();
alert("Phone number is invalid. Please try again.");
phoneNum.focus();
}
return blnResult;
}
<input type="text" name="homephone" size="12" onBlur="validPhone(this)"></input>
Does anyone know what is wrong with this? It is not working in Chrome or the Apple browser, but for some reason it works in IE 11.
Remove phoneNum.select() and phoneNum.focus().
Thoose instructions make fired a onBlur events, and you are in a loop with no end ...
You should turn your size attribute into maxLength.

What is the best JavaScript solution to limit the length of a textarea?

Is there a canonical solution for limiting the number of characters that someone can enter into a textarea?
I have server side validation of course, but would like to improve the user experience by adding client side code to simulate the experience you get with maxlength on an input[type="text"] so that users never see the "your input is too long" error message if they have javascript enabled.
My non-technical $0.02
Do what SO does in their comment fields, provide feedback as to what the user's character length remaining is and allow them to go past the maximum, but not submit > 300 characters. Here's why:
Allowing users to go over the maximum number of characters allows them to complete an idea. They can then go back and edit that idea. There's nothing worse than being at the end of a sentence and being unable to complete it.
Providing feedback to character length keeps people from having to guess what their length is at.
I would do it this way:
$ ('#textarea-id').bind (
'change input keyup keydown keypress mouseup mousedown cut copy paste',
function () { return ($(this).val().length <= maxlength) }
)
So many bingings just to be completely sure :-)
This will do it...
function textareaMaxLen(event) {
var max = parseInt(this.attr("maxlength"), 10);
if(this.value.length >= max)
this.value = this.value.substr(0, max);
}
$("textarea").keyup(textareaMaxLen).blur(textareaMaxLen);
Attach an onchange event to the textarea. There you can check if the value's larger than the appropriate or not. Example with jQuery:
$("#textarea-id").change(function (){
var text = $(this).val();
if( text.length > MAX ){
return false;
}
});
I've done it like this in the past:
<textarea onkeyup="checkLength(this);"></textarea>
Then implement this function:
function checkLength(control) {
if (control.value.length > 5) {
control.value = control.value.substr(0, 5);
}
}
It's a pretty basic example fixing the length to 5, but hopefully gives you the idea!

Categories

Resources