We have an order form which takes credit cards from mobile browsers: <input type="number" id="txtCCNumber" />
Also in addition to that we have a JavaScript which removes any non-integer characters that are inserted into the field:
$('input#txtCCNumber').keyup(function(e)
{
var ccnum = $(this).val();
$(this).val(ccnum.replace(/[^\d]/g, ''));
});
However we just realized that it appears that when people using an iPhone try to put their credit card in, iPhone automatically adds a comma every 3 numbers (because of the JavaScript).
Does anybody know a way to fix this JavaScript so it works?
I do not want to use type="tel". That is not a solution in this case.
Personally, I don't think credit card numbers are an appropriate use of input type="number". According to the spec:
The input element with a type attribute whose value is "number" represents a precise control for setting the element’s value to a string representing a number.
Credit card "numbers" are strings of digits, but they don't identify a particular numeric value, and it wouldn't make sense for a user to enter a credit card number using the up and down arrows that some browsers attach to the input field. Your best bet is simply to use input type="text".
Also, attaching that JavaScript to the keyup event is going to annoy people like me who want to enter their credit card number with separators because it's easier to spot check. Just let people enter their card number however they like and normalize it later.
I don't see a reason why you're using type="number" for a Credit Card number field since you're anyways removing non integer values using JS. Using type="text" would be apt here.
I created a fiddle and tested this on my iphone and it works properly.
http://jsfiddle.net/MH8gj/
Related
So I want to have an input of type number <input type="number"> and I want to RESTRICT users from ENTERING DECIMAL VALUE
Note: I'm hiding the spin buttons of the input type text. Know more here
EDIT: ANYTHING WILL WORK! EVEN JAVASCRIPT!
I searched a lot but found nothing.
I did find this answer but it basically blocks the use of any other key on the keypad except the number keys, so the basic problems occur such as the user cannot use backspace and cut the number entered, another problem is the user cannot use tab to change focus onto the next input.
Thank You!
Preventing user input can be done with JavaScript. I'd use the input event for catching values, as it's a unified interface, encompassing any input method you can think of keyup, paste, pointer events, touch events, etc...
document.querySelector('input').addEventListener('input', e => {
e.target.value = Math.round(e.target.value.replace(/\D/g,''))
});
<input>
But you really should not do it! For at least the following reasons:
Forbidding user input is, by and large, perceived as disrespectful and drives users away. In short, it reduces any user engagement metric you can think of (funneling, sales, visits, sharing, etc...). Don't take my word for it. Do some A/B testing: present the same form with and without blocking user input and look at the results.
Form elements are just tools to help users give you data. But they are completely by-pass-able. If you give me a form I can send whatever I want using it, by simply opening the browser console. The validation must be done on server side. If you're using the value to do something on client side, sanitize the input value in the method, without changing user input.
A respectful way to inform users decimal values are not valid is by making the input :invalid, using the pattern attribute ( e.g: pattern="[0-9]"), styling accordingly (e.g: :invalid { border-color: red }), and displaying an appropriate message.
Don't delete or block user input. They'll do it themselves if you tell them why the value is invalid.
When following web standards, your solution lasts. When you come up with hacks, there will always be the odd device in which your hack doesn't work. You don't know where things will be in 1-2 years from now, nevermind 5 or 10.
Last, but not least, have a closer look at Constraint Validation. You'll need to know and use it when creating quality UX and accessible forms.
This is one option for creating an input element using javascript to limit the values that can be entered. I create an array of allowed keys, including all the digits, backspace, and tab as you specified. I added an event listener for the keydown event, and if the key pressed is not in the allowed group, I prevent the default action, or prevent the value from being entered.
I also added an event listener to the paste event, as you could right click paste and enter information that does not meet the criteria. Instead of trying to validate pasted values I disable pasting all together.
If you have any questions, please ask.
const allowedKeys = [..."0123456789", "Backspace", "Tab"];
const myInput = document.querySelector("input");
myInput.addEventListener("keydown", e => {
const key = e.key;
const allowed = allowedKeys.includes(key);
if (!allowed) e.preventDefault();
});
myInput.addEventListener("paste", e => e.preventDefault());
<input type="number">
Background
I have a page that has 3 input elements which takes currency numbers
These input element of type number with jQuery handles which letting up to 2 decimal placing. If user tries to input 3rd decimal, it does not print which is great.
However...
Issue
When input already has valid 2d.p input such as 12.11 and wishes to highlight the field characters (such as click drag highlight to blue) to change/overwrite all, the jQuery handler think that its 3rd decimal input and does not print BUT what it actually needs to do is to overwrite the whole and start from the beginning.
So
Is there a way to check if the input field characters are highlighted?
I know that there is a way around this if my input has type="text" and just use selectionStart and selectionEnd BUT I want to keep it as type="number".
Code: jsfiddle DEMO
Any other suggestion to jQuery code handling 2 decimal place, I would appreciate
If I am understanding your issue correctly, try the following minimal update to detect if the user has 'highlighted' the input value:
if (CharAfterdot > 3 && !window.getSelection().toString()) { return false; }
So if a 'selection' is found via the above method (not empty / undefined) the code allows further input (in your case overriding via highlight).
Updated fiddle:
https://jsfiddle.net/qtr30w05/3/
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.
I'm testing my app on my mobile phone (samsung galaxy note II with chrome) and I have a problem with the numeric input fields.
In my app these fields can accept negative numbers, and on the browser it's all fine as I have the - button and also the arrow sliders (from html5) for choosing the number.
On the phone though the sliders are not rendered, and the browser recognise the input type=number, and just renders a simplified numeric keyboard, which doesn't contain the - sign, so I didn't see a way to insert the negative number I wish.
My app uses twitter bootstrap 2.3.2 with jquery, I'm not sure how to solve this problem.
here's the code for one of my input fields that work fine on my computer, but can't use them properly on my phone:
<input class="input-mini" data-type="distance_price" id="distance" label="false" name="distance" step="0.1" type="number" max="-0.1">
in the image you can see how the field in red is marked as wrong because it needs to be negative, but my keyboard doesn't let me insert symbols. including the - sign.
any clue?
The issue is specific to Samsung custom keyboard - hooray to vendors who think they're smarter than everyone. Here is another example of this issue at work
In short, there's no way to make the minus sign show up on Samsung Android numeric inputs. Here are a few workarounds I've run across:
1) Google Keyboard
The user can install a different keyboard (like Google Keyboard). Obviously not ideal to have people install something though.
2) Negate Button
As #Cris already suggested, add a button which will negate the value. If you've got the screen real estate then great.
3) Double Dot Trick
We ended up with a fairly ugly workaround where the user can press . twice and it will negate the number. Totally non-discoverable but an extra button wasn't an option for us.
https://gist.github.com/bendytree/936f6b9b4c0e10138b7e9158b5fd05d9
Make an extra input field. A "sign" checkbox, selecting natural or negative integers.
Then hook the onchange event of the checkbox so that you update the number view to reflect the chosen sign.
If you use the value attribute (value="-0.1") to load an initial negative value then you will have the minus sign pre-loaded for you.
<input class="input-mini" data-type="distance_price" id="distance" label="false" name="distance" step="0.1" type="number" max="-0.1" value="-1">
If you returned here because the Double Dot Trick from above stopped working... It seems an update to how input type="number" fields are handled keeps the second "dot" from even registering as a keystroke stopping the Double Dot from working. In my case, I changed the test line in the JS to
if (lastkey === "." && (key === "." || e.originalEvent.inputType == "deleteContentBackward")){
to create the equally hacky "Dot Backspace Trick"
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.