I have a field that accepts the year, so I have created
input type="number"
and implemented keydown event to restrict user to enter more than 4 digits.
Now I'm facing an issue and need help in figuring out the logic. Following is the case:
Enter 4 digits in the textbox
Select entered text using SHIFT + Arrow Keys
Now if you type a number it should replace the data but since I have barred it, it will not. Need to cover this case.
Also find code in following JSFiddle.
I also have lot of css and validation on input[type=number], so cannot change to input[type=text].
Also same form is used on mobile devices, and when user selects textbox, numeric keyboard should appear.
Edit 1
while searching for option, I found a JSfiddle that could direct us to right direction.
Issue here also is input[type=number] does not support selection property. Reference
As an alternative, we have decided to move to input[type=tel]. This would work in similar fashion, but will allow us to use maxLength attribute. Still if anyone has a better way, please share.
HTML:
<input type="tel" class="year" maxlength="4" data-temp="">
jQuery:
$(document).on('input', '.year', function(){
var txt = $(this).val();
if(isNaN(txt) || txt > 9999){
$(this).val( $(this).data('temp') );
return;
}
$(this).data('temp', txt);
});
JSFiddle
May be this will work , you can use the Regular Express to validate only number and
^[0-9\.\-\/]+$
and also you can use the .length method to insure that you have specific length
You can't submit an invalid value in this case:
<form>
<input type=number min=0 max=9999 required />
<input type=submit value=Submit />
</form>
So I have moved my code to input[type=tel] and Updated JSFiddle
If you check, I have added 2 events
Keydown to restrict from entering any invalid key.
Blur event to check if entered value is number only or not.
Now you might be thinking, if I have already restricted user to enter only number, how can he enter incorrect value.
Explanation
In my implementation, I have used keydown and using keycode, I'm allowing/blocking. Interesting case is when user press and holds shift key. Now on keydown, I get same keycode but value is different(A special character). So checking the integrity on blur.
A better way would have been handling keypress and keydown together and I'll update fiddle and update my answer, but for now I guess this has solved my problem.
Thanks you all for all comments/answer. Also kindly let me know if there are any better ways to implement.
Related
I have used the following code
$('#id1').keypress(function(e){
if ($('#mail_mobNumber').val().length > 9) {
e.preventDefault();
});
So, if I enter 10 numbers, I cannot enter anything more, and that is the goal.
But, on the other hand, after I enter 10 digits and if I select the entire field using Control + A, and tries to enter something, instead of the text getting replaced by what I am entering, nothing happens.
I understand that it is due to the impact of the above code, but is there anyway to achieve this, that is, allowing me to overwriting input after pressing Control + A.
You can simply use the maxlength attribute in the input tag instead.
<input type="email" maxlength="10">
I have a form which I want to only allow numbers and decimal 1 place. This works in Chrome and IE but not in Firefox. It will remove the dot from Firefox. What am I doing wrong?
$(document).on('change keyup', '.Monday, .Tuesday, .Wednesday, .Thursday, .Friday, .Saturday, .Sunday', function () {
var sanitized = $(this).val().replace(/[^0-9.]/g, '');
$(this).val(sanitized);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input class="form-control full-width Monday" name="monday" id="monday" type="number" />
Looks like a bug in Firefox. It's easy to confirm that it's not about regex: in fact, any reassignment in keyup handler seems to break it up, effectively disallowing floats. For example (done with vanilla DOM API to prevent potential side-effects; it's the same with jQuery, of course):
document.getElementById('demo').addEventListener('keyup', function() {
var oldValue = this.value;
console.log(oldValue);
this.value = oldValue;
});
<input class="demo" id="demo" name="demo" type="number" />
Note that there's a subtle difference in keyup phase for numeric and non-numeric characters. For example, if there's already 4 entered in the control, and you press 2, the logged value will be 42. However, it still be 4 if you press . instead. Chrome and IE seem to disregard this difference, Firefox is a bit more straightforward.
Fortunately, it's quite easy to find a workaround for the bug - just listen for input event instead (MDN docs). Not only it's guaranteed to fire after the value is changed, it also handles such things as mouse-triggered copy-paste.
There are differences in implementation of the <input type="number"> element in different browsers, but when you use it, you should leave it to that element to perform the validation. And it does that by showing a red border (implementation dependent) instead of taking out invalid characters, because most believe that the latter solution is not user-friendly -- you don't want them to think their keyboard is broke.
There are the following issues playing in your case:
When you type a point after a series of digits, that is considered valid by your code, but by assigning it back to the input, it is interpreted as a number, and so the final point is removed from it.
When you first type a series of digits and then a letter the whole input gets cleared. This is because in Firefox the value you get from the input is already validated, and if not valid, the empty string is returned, even though the input still shows the characters.
The thing really is that you should choose whether you leave it to the browser or to your code to validate in the input. In the latter case, just remove the type="number".
I've added an on 'change' event listener to a type=email input element. When I add a couple space characters into the email field, then lose focus on that element, the change event doesn't seem to be firing.
However, this exact scenario works just fine with type=text input elements.
What's going on?
$('input[type="email"]').change(e => {
console.log('Triggered!');
});
Browser: Chrome Version 63.0.3239.132 (Official Build) (64-bit)
I originally said that it looks like there is an automatic trim operation performed on email fields because the length of the value is coming back at 0 after typing some spaces and leaving the field, but upon returning to the field, the spaces remain in the element, so they aren't getting trimmed out.
I suspect that, because spaces are not valid for this input type, they are not considered part of the value, thus the value doesn't change when you enter them and the change event doesn't fire.
Type some spaces in the field and then hit TAB to leave the field, but then return to the field. The spaces will still be there.
$('input[type="email"]').on("blur", function(e){
console.log(this.value.length);
});
$('input[type="email"]').on("change", function(e){
console.log("Change fired!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="email">
You can use something like that:
$('input[type="email"]').on('focusout', {
console.log('Triggered!');
var $trig = $(this);
$trig.attr('trimmed', $trig.val().toString().trim());
$trig.val( '').val($trig.attr('trimmed'));
});
But, as answered above, input[type="email"] does not count whitespaces. It is only works as fast hack;
I am facing the same problem with React, and I don't want to reflect the error on the onBlur event (as other solutions here). I don't think an error should be reflected in any input by the simple fact of removing the mouse from that input. For me that's not User friendly,... AT ALL.
Why?
Because the User might have decided to remove the mouse from that
Input only because he/she simply wants to copy something from somewhere else first,... and then past it there (and/or to past it somewhere else). So technically there is no mistake there yet.
Because I simply want to fill another input field of the form first.
Why? Becase that's precisely the field's value I already copied from
somewhere else, so that's the value I have stored in clipboard, and
it doesn't goes where my mouse landed by default. Or simply because
I just want to! I'm the User, so I can choose the order to
fill the form!
For me is more than enough with validating what the User has written and/or removed/deleted from the Inputs (onChange validation) AND also what the User finally decides to send (onSubmit validation). A proper combination of onChange and onSubmit validation is the perfect healthy balance between thoroughness and User friendly.
A Solomonic "solution":
I am using a custom validation hook. As I can not change the behavior of the input with a type email regarding the white spaces in an OnChange event,... then I decided to use a workaround, which is simply avoiding the typing of white spaces and that's it, as the onChange event won't trigger anyway.
const preventWhiteSpaceOnKeyDown = (e) => {
if (e.key === " ") {
e.preventDefault();
}
}
.
.
.
<input
type={"email"}
id='commentEmail'
name='commentEmail'
required={true}
autoFocus={true}
ref={emailInputRef}
value={emailState}
onChange={emailInputChangeHandler}
onKeyDown={preventWhiteSpaceOnKeyDown}
/>
This is not a "solution". There is no clean solution for this. But after this at least my input[type=email] element won't hold useless white spaces.
input[type="email"] does not fire change event, use blur event instead:
$('input[type="email"]').blur(function(){
console.log('blur event is fired.');
});
I have an element:
<input type="number">
When I type in $500, it fails validation, so
console.log("el.value");
//returns ""
This is expected.
Here's the question:
How can I check that there is content?
I'm trying to show/hide placeholder text (no, I can't use the native stuff). It needs to be type="number" because I need to force the mobile number keyboard.
Any thoughts?
Update:
From the responses below I can see that I wasn't clear enough in my question.
1) I need to use JavaScript to tell me whether there is content in the input. (I don't need to extract it, I just need to see whether there is content).
This is tricky, because invalid content (like putting words in a number input field) means the value="" even if there is content typed in.
This is the exact problem I need to solve.
inputEl.validity.valid might work but I can't find any docs on how well it is supported across browsers.
Check if you can do something with that :
html
<input id="my-input" type="number">
js
$(document).ready(function(){
$('#my-input').on('input', function(){
console.log($(this).val());
});
});
At mobile device specially Samsung append value in field do not throw key press event,
you can validate the field with onChange="check(this)"
if (variablename==""){
//no content
}
or
if (variablename.length==0){
//no content
}
If the only reason you need to force the input type to be a number is for the number-pad, why don't you instead make type="text" and pattern="\d*"? This way you can handle and check the input any way you'd like, but still, force the number-pad to show.
<input type="text" pattern="\d*">
This was the one that actually answered it:
How to get the raw value an <input type="number"> field?
Basically you can check input.validity.valid or input.validity.badInput.
Not supported in IE but good support elsewhere.
More details on it here:
https://developer.mozilla.org/en-US/docs/Web/API/ValidityState
I want to re-invent the password input in HTML.
Okay, here is the work I'd done:
http://www.symplik.com/password.html
(It just a plain html code, nothing really fancy :>)
The "password" is indeed a text input, and I used the onkeyup event to rewrite the input to masking characters.
There're two problems:
(1) backspace or delete cannot be detected
(2) if I type very fast, some characters cannot be captured promptly.
For problem (1). it is partially solved by checking the length of text in the password field and the stored password. Not a very elegant solution anyway.
For problem (2), I'd tried to insert some time delay function in between but still fail. I'd make the field readOnly after every keyUp but it still behaves the same.
Why not use
<input type='password'>
It masks the input for you. No need for javascript.