regex working in chrome and ie but not firefox - javascript

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".

Related

Firefox forces 0 to input value when the desired value is anther form of 0. Ex: 00.00. Is there anything that could be done?

Firefox forces all forms of zero to be 0. We are being asked to make the front end consistent if possible. So when 0 comes in as the value we want to show 00.00 as this is a financial site. I tested this outside my current code with both jquery and regular javascript.
document.getElementById('txtQuantity').value = '00.00';
$('#txtQuantity').val('00.00');
Both of those simple calls to set 00.00 come out as 0. I thought about input masking this but we don't want to force clients to type out decimal placeholders when all they want to input is an integer.
I suspect the issue is type="number" as #Rory hinted at. Given <input type="number" value="00.00">, Firefox will show an element that contains the value, 0.
It's not exactly semantic, but in my experience tel is more consistent across browsers. Note that this will also get rid of the spinner buttons (which in my use cases is preferred, but might not be in yours):
<p>number: <input type="number" value="00.00"></p>
<p>tel: <input type="tel" value="00.00" pattern="\d+\.\d+"></p>
Firefox:
 
Chrome:
 
Edge (FWIW):
 

Keydown event issue on HTML textbox

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.

input type=number not possible to insert negative numbers on mobile phone

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"

iPhone adds commas to input number field due to JavaScript

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/

How might I implement immediate text submission when the enter key is pressed in a textarea?

Duplicate:
Submitting data from textarea by hitting “Enter”.
I've got a textarea and a submit button:
<textarea id="chat"></textarea>
<input type="submit" value="Submit" onclick="send_msg();">
The value of the of the texarea is submitted when Enter is hit:
textarea.onkeyup = function(e) {
alert(e.keyCode);
e = e || window.event;
if (e.keyCode === 13) {
send_msg();
}
return true;
}
Problem is to make the textarea submit its value prior to letting the cursor to jump to the next line. How's it possible to do that?
The trick is to stop the browser from executing the default behaviour on key down and key up. To do that, simply return false in your onkeypress/onkeyrelease handlers when you detect keycode 13.
One issue this ignores is users running input method (editors) -- eg. non-latin text entry. The IME i am familiar with is the Kotoeri Hiragana IM on OSX, but there are numerous others both for japanese (Kotoeri alone has multiple different input modes, and there's at least one other major one called ATOK), in addition to modes for hangul, traditional and simplified chinese, as well as numerous other less well known languages. And these input methods exist on all major platforms (esp. Win, Mac, and Linux).
The problem that they introduce from the point of view of code similar to what you're attempting is that the exact physical keypresses does not necessarily correspond to the actual input that the user is entering.
For example typing the sequence of characters toukyou<enter> under hiragana by default will produce the string とうきょう, note that there is no <enter> in the resultant text because enter confirms the composed text. But in addition to this the actual sequence of characters that appears changes as the input is typed:
t // t
と // to
とう // tou
とうk // touk
とうky // touky
とうきょ // toukyo
とうきょう // toukyou
If memory serves when i implemented this in webkit it was necessary to make the keyCode be 229 on keyDown for all keys typed in an IME (for compat with IE) -- but i cannot recall what the behaviour of keyUp is.
It's also worth noting that in some IMEs you won't necessarily receive keydowns, keypress, or keyup. Or you will receive multiple. Or they're all sent together at the end of input.
In general this is a very... unclean... portion of the DOM event implementations currently.
e.preventDefault();
This text is here because stack overflow insists that there is no useful answer with less than 30 characters. Guess how I feel about that?

Categories