Most web developers know that to restrict only numbers to a form input, you can do something like this:
$(function() {
$("#foobar").keypress(function(e) {
if($.inArray(e.which, range(48, 57)) == -1) {
e.preventDefault();
return false;
}
});
});
function range(start, end) {
var range = [];
for(var i = start; i <= end; i++) {
range.push(i);
}
return range;
}
Unfortunately, this does not quite get the job done on an Android with the default browser. (iPhone and Other Android browsers have not been tested, so they could suffer from the same issue. Tested on an iPhone 4S, which did not have this issue.)
On an Android, let's say you first type "f". Nothing happens. Awesome. Wait just a minute. You then type "a". What happens? The "f" is put into the input field! You type "c", the "a" is put into the field. And so on. Whatever the previously-entered character is, that's what's put into the field.
Here's a jsFiddle that demonstrates the issue.
The fiddle works fine on a desktop, but try it on Android (phone or emulator). I've tested with Android 2.3.6 and 2.2.
Anyone run into this before? Any direction would be greatly appreciated! For now, the workaround is to remove non-numeric characters immediately afterwards (in the keyup event).
Update: Here is a fiddle that shows that preventDefault() is being reached. The problem seems to be that rather than preventing, it's simply delaying (until the next event).
A completely different approach would be using <input type="number"> and relying on the browser to provide the appropriate interface/filtering (which mobile browsers are prone to). It does not fix the code, but should circumvent the problem, which looks like a bug, to be honest.
A wild guess: Maybe Androids register the input at the keydown stage. You could try both events.
Ok I played with this a bit and this is running fine on my andriod:
var reserved = [0,8]
$(function()
{
$("#foobar").keypress(function(e)
{
if($.inArray(e.which, reserved) < 0 && ((e.which < 48) || (e.which > 57)))
{
e.preventDefault();
return false;
}
});
});
http://jsfiddle.net/HW794/1/embedded/result/
Possible that droid does not like the call to the fn? (range)
Related
My problem is, is that the numpad's "/" key triggers the search bar in Firefox. I would like to prevent this from happening.
I'm currently working on an online Calculator, and ran into the problem described earlier. The reason why I would like this not to happen, is because you obviousely can't type in a division thanks to this feature. The page is only meant to run in Firefox, and it's just a little help for my little brother, so it doesnÄt have to be the most professional solution - if it works, it's fine. I've already tried the preventDefault method, but that doesn't change anything.
Any help is appreciated!
(Sorry if this question was already asked before, or it doesn't append to the rules, I'm totally new to StackOverflow)
window.addEventListener("keyup", function (event) {
let signs = ["*", "-", "/", "+"];
event.key.preventDefault;
if (!(isNaN(event.key)) || signs.includes(event.key)) output.value += event.key;
else if (event.keyCode === 8) {
output.value = output.value.slice(0, -1);
}
})
//This is a snippet of my code right now, but the event.key.preventDefault part doesn't work for my problem
I think you should use preventDefault like this:
event.preventDefault();
I don't know whether this will block the search box or not, but you can call preventDefault like this.
I spent way too much time trying to understand the problem here. I am working with a HID Barcode Scanner, and am able to get the device information. But I am unable to get a hold of the HidDevice object even with the right device id. It always return null. Here is what I have:
var selector = Windows.Devices.HumanInterfaceDevice.HidDevice.getDeviceSelector(parseInt('0x1', 16), parseInt('0x6', 16));
Windows.Devices.Enumeration.DeviceInformation.findAllAsync(selector, null).then(
function (deviceInfoCollection) {
if (deviceInfoCollection.length > 0) {
for (var i = 0; i < deviceInfoCollection.length; i++) {
var id = deviceInfoCollection.getAt(i).id;
return Windows.Devices.HumanInterfaceDevice.HidDevice.fromIdAsync(id, Windows.Storage.FileAccessMode.readWrite);
}
}
else {
throw "No Devices Discovered.";
}
})
.done(function (device) {
if (device != null)
successCallback(device.name);
});
I added these device capabilities in my manifest file:
<DeviceCapability Name="humaninterfacedevice">
<Device Id="any">
<Function Type="usage:0001 *"/>
</Device>
</DeviceCapability>
I'm going through the same issue now. The only thing I see in your code that strikes me as odd is the following manifest tag:
<Device Id="any">
Usually, the "any" value works. But I've had issues arise where the vendor and product id are required; I'm not quite sure why, but I think it's based off the type of device/usageid. I would try hardcoding the vendor and product id's to see if it makes a difference.
Another thought: I'm guessing by the usage tag that your scanner is configured as a keyboard. You can check to see if your scanner can be configured as a non-keyboard HID device, which helped me personally. I see other people on the internet having issues where an HidDevice is returned as null because another program is using that device; in your case, the OS might already be using the keyboard and locking it out somehow.
Best of luck!
Is there a cross-browser way or cross browser solution to capture the "Save" keyboard shortcut in the browser? For example, in GMail if you use CMD + S it will save the email and not prompt the browser to download the webpage (default behavior). I would rather use a cross browser solution than add event listeners and write it from scratch.
One cross browser solution is to check out keycode.js. Less hassle to worry about looking for browser caveats and such.
I know it's old, but it still works. You can check out its demo too!
Looking at the demo, and the header comments in the .js, something like this?
document.onkeydown = function(e) {
e = e || window.event
var k = KeyCode.translate_event(e);
if( k.ctrl && !k.alt && !k.shift && k.code == 83 ) //83 is the code for s
save(); //Magic function
if(e.preventDefault) {
e.preventDefault();
}
return false;
};
I bought some files through codecanyon.net and they've been working fine on all browsers. Just recently I noticed they weren't working in Chrome.
The code is really big and I've tried to change some things through trial and error on the js file but was unsuccessful. You can see the slider at http://miguelsart.com/scroller-test.
As you can see, the captions are supposed to be hidden and once you hover they have slide up. But with Chrome, the captions appear automatically and nothing happens when you hover.
I think something is wrong in this part of the code:
//init captions
Scroller.prototype.initCaptions = function() {
var $captions = this._$slides.find(">p:first");
if (this._displayCaption) {
var padding = $captions.outerWidth() - $captions.width();
$captions.css({width:this._slideWidth - padding, display:"inline-block"}).click(preventDefault);
if (this._captionPos == OUTSIDE) {
var heights = $captions.map(function() { return $(this).height(); }).get();
var maxHeight = Math.max.apply(Math, heights);
$captions.css({top:this._captionAlign == TOP ? 0 : this._slideHeight, height:maxHeight});
this._extHeight = $captions.outerHeight();
if (this._captionAlign == TOP) {
this._extOffset = this._extHeight;
}
$captions.addClass("outside");
}
else {
if (jQuery.browser.msie && parseInt(jQuery.browser.version) > 6 && parseInt(jQuery.browser.version) < 9) {
$captions.addClass("ie-inside");
}
else {
$captions.addClass("inside");
}
}
}
else {
$captions.hide();
}
}
I've tried messing around replacing display for opacity or for visibility but nothing worked. Does anyone have any clue what might be wrong?
Thanks in advance!
I believe I've figured out what's wrong with the author's implementation, and you are correct, it has to do with the latest version of Chrome.
On line 43 of jquery.wt.scroller.js
this._mouseoverCaption = window.Touch ? false : opts.mouseover_caption;
The author of the plugin is testing for native touch capabilities (by determining if window.Touch is defined). Chrome must've recently added native touch API capabilities in a recent version.
So what the author was going for, was saying that 'you can't hover on a touch device, so we can't show the captions on hover on a touch device so we'll just always show them' - which is logically.
However, just because touch capabilities exist, however, doesn't mean that touch input is the default (as in this case). Modernizr solves this issue (for now) by performing the following conditional:
if(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
Something tells me this will also soon be broken. (https://github.com/Modernizr/Modernizr/blob/master/feature-detects/touchevents.js#L42)
So, long story short (too late, I know) add this to the plugin code:
Add this to line 7 (push all lines down one):
var TOUCH = ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch;
Find and replace all occurrences of window.Touch with TOUCH in the plugin code.
Tell the author of the plugin I'll send him a bill. :)
I have a strange bug where I am doing an ajax load from an input. I realize that this may be a stupid way but it was the only way I found to get IE to cooperate with using the enter key. I then had a separate issue of where the submit in IE kept opening a new window rather than just using Ajax GET. So.. I ditched the form altogether and I am trying to do everything with javascript.. something like this :
<input class="myInput" type="text"></input>
<img src="submitbutton" class="submitIt" />
I am starting the ajax function with :
$('.submitbutton').click{function() { ajaxFunction(); });
which works fine.
and also when the user hits enter:
$('.myInput').keydown(function(e){
if (e.keyCode == 13) {
ajaxFunction();
return false;
}
which works.. for the first entry. But then if you enter a second number it makes that ajax request 2 times, a third number = now 3 simultaneous ajax requests to the same place are happening, ad infinitum ...
I am pretty sure the problem is the wacky way I set up validation. The keydown function is in an else {} statment like this and will not work until there are exactly 9 numbers in the input.. here is part of it :
if ( len !== 9 )
{
if ( len == 1 )
{ y.hide(); n.show(); valInput.text("You need 8 more numbers");
}
else
{
if ( len == 2 )
{ y.hide(); n.show(); valInput.text("You need 7 more numbers");
}
...
}
else {
$('.myInput').keydown(function(e){
if (e.keyCode == 13) {
ajaxFunction();
return false;
}
}
Sorry I dont have live code that is accessible and it would take me a while to set one up but if that is what needs to happen I will do it.
I have a strange bug where I am doing an ajax load from an input. I realize that this may be a stupid way but it was the only way I found to get IE to cooperate with using the enter key
Might be the IE version you are using. But hitting the enter key triggers a submit here.
I then had a separate issue of where the submit in IE kept opening a new window rather than just using Ajax GET. So.. I ditched the form altogether and I am trying to do everything with javascript.. something like this :
You should really need to find out why that happens in stead of trying to write hacks. It's part of the game as well as the learning process as well as it is just the way to do it.
Why don't you just use .submit() and a 'normal' submit button like:
<form action="#">
<input type="text" name="myInput">
<input type="image" src="submitbutton" class="submitIt">
</form>
$(function() {
// use this instead of clicking on submit or enter key pressed
$('form').submit(function() {
// get character count of input
var char_count = $('input[name="myInput"]', this).val();
// validate it
if (char_count != 9) {
// still need to initialize y, n and valInput
y.hide();
n.show();
// watch out this may give negative numbers
// this will take care if the error to be displayed. way better than using lots of ifs :)
valInput.text('You need '+parseInt(9-char_count, 0)+' more characters');
return false;
}
// can be uncommented if you still want to use AJAX to submit your form, but really it is not needed.
//ajaxFunction();
//return false;
});
});