`String.fromCharCode(keyCode)` doesn't work in Firefox - firefox

String.fromCharCode(keyCode) doesn't work in Firefox.
For example
I press the semicolon key and it throws the 1/4 sign.
The number pad throws letters.
I am using this to do some field validation, because the event.key attrubute is not supported in FF.

Use event.which for FF. You can refer to this example

Keycode is the numeric identifier of the key on the keyboard. It's pretty much completely unrelated to the charcode, which is the Unicode codepoint of the character produced.
So using a keycode as an argument to fromCharCode will almost certainly give you garbage.
What are you actually trying to do with the keycode, and why?

Instead of event.keyCode try event.charCode. It will work in chrome and firefox.

$('#Name_Var').keypress(function (event) {
event = event || window.event;
var charCode = event.which || event.keyCode;
var charStr = String.fromCharCode(charCode);
// FireFox key Del - Supr - Up - Down - Left - Right
if (event.key !== undefined && event.charCode === 0) {
return;
}
//Only Num
if (!/^([0-9])*$/.test(charStr)) {
event.preventDefault();
}
//Num and letters
if (!/^[a-zA-Z0-9]+$/.test(charStr)) {
event.preventDefault();
}
});

Related

CKeditor changes character "š" to "š" in source

For my site I am using CKeditor to add/edit content and I noticed when I write character š in source code it is changed to š - this causes problems when I do search in the database, so I am wondering how to fix this, so that that character will stay written in the source code the same way (not changed)?
I can fix this by adding this to config:
config.entities = false;
But with this, everything is disabled (even quotes, double quotes,... are now not changed in source), so this is not the best solution, right?
I also tried with those settings, but they don't help:
config.IncludeGreekEntities = false;
config.IncludeLatinEntities = false;
What else can I try? Is there any way to manually set that some characters should not be converted?
This command seems to work, I no longer have problems with š (other special chars are still converted - like quote, which is fine):
CKEDITOR.config.entities_latin = false;
If it causes an issue with your search implementation, it is not only a "š" character which will be an issue here but all special characters which may be used for search. I don't think CKEditor has a config to whitelist entities which should not be encoded.
I would suggest just decoding this characters after getting data from CKEditor, like:
var map = { 'š': 'š', 'à': 'à' };
editor.getData().replace( /š|à/g, function( m ) { return map[ m ] } );
----- EDIT:
To integrate it with CKEditor one may use toDataFormat event:
var editor = CKEDITOR.replace( 'editor1' ),
map = { 'š': 'š', 'à': 'à' };
editor.on( 'toDataFormat', function( evt ) {
evt.data.dataValue = evt.data.dataValue.replace( /š|à/g, function( m ) { return map[ m ] } );
}, null, null, 16 );
See working example on codepen.
Only had deleted "scaron" and "Scaron" from ckeditor.js source.

How to write KeyBindings

I am developing a Java 2D Game, in which I have used a KeyListener, but as you probably can guess, it has focusing issues, mainly when the Player is running and you keep the same key pressed for long, for example pressing "W" to run forward, but after some seconds of keep pressing W, the KeyListener dies and no key works, I want to use KeyBindings, as most people suggest it for game development, but I cannot find any usefull tutorials, most of them use some form of Buttons, and other useless features for my game, so how can i avoid the KeyListener from losing focus, or how can I write a simple KeyBinding code, that only moves the player, and other simple stuff used in a game.
This is the kind of Key Binding that I want, I KNOW IT DOES NOT WORK, it is an example:
component.getInputMap().put(KeyStroke.getKeyStroke(VK_W),
"move forward")
component.getActionMap().put("released",
releasedAction);
if(releasedAction == true){
Player.playerSpeedY = 7;
} else{
Player.playerSpeedY = 0;
}
FWI: this is the current KeyListener code:
if(HUD.PlayerHealth > 0){
if(key == KeyEvent.VK_W) {Player.playerSpeedY = -5; keyDown[0]= true;}
if(key == KeyEvent.VK_S) {Player.playerSpeedY = 5; keyDown [1]= true;}
if(key == KeyEvent.VK_A) {Player.playerSpeedX = -5; keyDown [2]= true;}
if(key == KeyEvent.VK_D) {Player.playerSpeedX = 5; keyDown [3]= true;}
}
I keep looking for Actions and Input maps tutorials, or KeyBinding ones, and I just don't find anything useful, another dough, the component in action and input map, what is it for?, should my entire code be based on that, and is there any way to only make the action map move the player, and only that?
Try something like this:
this.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0, false), "right");
this.getActionMap().put("right", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
//Do Something Here
Player.playerSpeedX = 5;
}
});
How to use KeyBindings

JQM Toggle flip switch error calling refresh

i am new to JQM.
I am trying to set up a switch control for home automation. There are switches for every room to be controlled by phone or computer.
THe issue I am having is that I have one toggle flip switch which should switch the whole group on or off. The problem is the updating of the other toggle flip switches on the side, eg. when selecting 'off' for the whole group all switches should be changed to 'off' or vice versa for the 'on' option. if any of the other switches is selected the 'Whole Group' switch should not be changed.
I have tried all kinds of refresh options but either the page hangs completely or I get the following error
Error: cannot call methods on slider prior to initialization; attempted to call method 'refresh'.
I have tried all different answers given in the forum, but none is working on Chrome, Firefox or iPhone Safari.
$(document).ready(function () {
$(".tswitch").bind("change", function (event, ui) {
var n = $(this).val();
console.log('Start value n: ' + n);
if (n == '0') {
$('.tswitch').val('1');
$('.tswitch').slider("refresh");
<!--$('.tswitch').val('1').trigger('create').slider("refresh")-->
console.log('0 toggle: ' + $(this).val() + ' value n: ' + n);
} else {
$('.tswitch').val('0');
$('.tswitch').slider("refresh");
<!--$('.tswitch').val('1').trigger('create').slider("refresh")-->
<!--var fts = $('.tswitch');-->
<!--fts.val('0');-->
<!--fts.trigger('create');-->
<!--fts.slider('refresh');-->
console.log('1 toggle: ' + $(this).val() + ' value n: ' + n);
}
});
});
the code is on http://jsfiddle.net/PdkQ5/98/
also tried JQM 1.8 and 2.0

Select hyphenated word with double-click

UPDATE: Per the recommendation below, here's specifically what I'd like to do: If I double-click the mouse cursor anywhere from the "b" to the "n" of "blue-green", I want all of the word "blue-green" should be highlighted. How can this be done? Currently, depending on where you click, it treats "blue-green" as three separate character strings. So, if you double click between the "b" and "e" of "blue" it highlights only "blue" and not "-green." If you double-click the hyphen, it highlights the hyphen alone. And if you double-click between the "g" and "n" of "green" it highlights only "green" and not "blue-".
ORIGINAL: When I double-click a hyphenated word or set of characters (e.g. "123-abc" or "blue-green" etc.), only the part of the word that I double-clicked is highlighted. I'd like the whole word to be highlighted.
I'm using Windows 7 Pro. If it needs to be done on a per-application basis, I'm most interested in fixing it for Google Chrome, but any Windows-compatible web browser would be OK.
Old question, but I happen to have been working on the same issue. Here's my solution:
jsFiddle.net
"use strict"
// Tweak to make a double-click select words with hyphens
//
// As of 2016-0816, None of the major Mac browser selects whole words
// with hyphens, like "ad-lib". This tweak fixes the hypen issue.
//
// Note: Firefox 48.0 doesn't automatically select whole words with
// apostrophes like "doesn't". This tweak also treats that.
;(function selectWholeWordsWithHyphens(){
var pOutput = document.getElementById("output")
var selection = window.getSelection()
// Regex designed to find a word+hyphen before the selected word.
// Example: ad-|lib|
// It finds the last chunk with no non-word characters (except for
// ' and -) before the first selected character.
var startRegex = /(\w+'?-?)+-$/g
// Regex designed to find a hyphen+word after the selected word.
// Example: |ad|-lib
var endRegex = /^-('?-?\w+)+/
// Edge case: check if the selection contains no word
// characters. If so, then don't do anything to extend it.
var edgeRegex = /\w/
document.body.ondblclick = selectHyphenatedWords
function selectHyphenatedWords(event) {
if (!selection.rangeCount) {
return
}
var range = selection.getRangeAt(0)
var container = range.startContainer
var string = container.textContent
var selectionUpdated = false
if (string.substring(range.startOffset, range.endOffset)
.search(edgeRegex) < 0) {
// There are no word characters selected
return
}
extendSelectionBackBeforeHypen(string, range.startOffset)
extendSelectionForwardAfterHyphen(string, range.endOffset)
if (selectionUpdated) {
selection.removeAllRanges()
selection.addRange(range)
}
function extendSelectionBackBeforeHypen(string, offset) {
var lastIndex = 0
var result
, index
string = string.substring(0, offset)
while (result = startRegex.exec(string)) {
index = result.index
lastIndex = startRegex.lastIndex
}
if (lastIndex === offset) {
range.setStart(container, index)
selectionUpdated = true
}
}
function extendSelectionForwardAfterHyphen(string, offset) {
if (!offset) {
return
}
string = string.substring(offset)
var result = endRegex.exec(string)
if (result) {
range.setEnd(container, offset + result[0].length)
selectionUpdated = true
}
}
}
})()
It's a standard through all programs that it will do that because they all run off the operating system's typing configuration/program thing. To fix it you would need to do something in System32. I don't know what you would need to do but I suspect this is your problem. You should probably go into more detail though about specifically what it is you want.

HTML5 Input type "number" in Firefox

I am working on an app that is only used by a few people in-house, so I feel comfortable telling them to only use Firefox or Chrome, so I can use HTML5.
I was working on a very simple feature:
<style>
input:invalid { background-color: red; }
div.box {
border-color:#000;
border-width:thin;
border-style:solid;
}
</style>
<input type="number" name="id"> <small>(if the box becomes red, make sure you didn't put a space)</small>
It works great in Chrome: it becomes red and won't let you submit, without me coding anything else.
Firefox ... not so much. It acts as if I had a "text" type.
Is that a known issue? Workaround?
Thanks
First of all, are you using Firefox 4? HTML5 forms has much better support in version 4.
This page has details on HTML5 forms and the current bugs
https://wiki.mozilla.org/User:Mounir.lamouri/HTML5_Forms
Update: If the browser does not support the HTML5 features you want to use, try Modernizr. It uses Javascript to enhance support. It's documentation has information about input types.
Is that a known issue?
Yes. Unknown types are treated as text. (And types which only appear in draft specifications tend to be unknown by many browsers)
Workaround?
JavaScript
input type="number" is not implemented in Firefox yet as of version 25 (November 2013).
Bug 344616 is the relevant ticket in Bugzilla#Mozilla: https://bugzilla.mozilla.org/show_bug.cgi?id=344616
Update 10 March 2014 - Good news! Looks like the ticket was fixed in Firefox 29, scheduled for release on 29 April 2014.
Update 30 April 2014 - Confirmed, I just gave it a try, and Firefox 29 has support for input type="number".
No browser gets this yet. Mileage may vary, but there is definitely work to be done in all browsers.
Opera will show you an UI letting you click arrows up and down to increase or decrease the number.
You can however submit the form even if anything but a number has been entered. Accessibility is not perfect yet, but at least you can also use the arrows of the keyboard to increase and decrease the number.
Chrome has no UI for the number yet, thus there is no help or no visual hint that a number is expected. Chrome also has no real error message. Turning the input border slightly red is definitely not good enough as a default and it is totally inaccessible. Chrome basically is the worst offender of all browsers when it comes to accessibility, e.g. zero support for ARIA.
You are using the :invalid pseudo-class to make the entire input widget red. Please recognize that this may be clearer than the default styling in Chrome, but it is still not an accessible solution. Since Chrome does not support ARIA, the bad news is that even if you'd provide a text error message through JavaScript, a blind user, or anyone else using a screen reader, might not hear it at all.
Firefox may be late to this game, but please recognize the fact that Mozilla have very strict shipping criteria for its features, while Chrome plays around with no thought about consequences.
i am using firefox, i had the same issue developing my input type number typing caracters and spaces etc...
anyway i m using angular 2 in this examples, its almost similar to javascript, so you can use this code in every case :
here is the html :
<input class="form-control form-control-sm" id="qte" type="number" min="1" max="30" step="1" [(ngModel)]="numberVoucher"
(keypress)="FilterInput($event)" />
here is the function FilterInput :
FilterInput(event: any) {
let numberEntered = false;
if ((event.which >= 48 && event.which <= 57) || (event.which >= 37 && event.which <= 40)) { //input number entered or one of the 4 directtion up, down, left and right
//console.log('input number entered :' + event.which + ' ' + event.keyCode + ' ' + event.charCode);
numberEntered = true;
}
else {
//input command entered of delete, backspace or one of the 4 directtion up, down, left and right
if ((event.keyCode >= 37 && event.keyCode <= 40) || event.keyCode == 46 || event.which == 8) {
//console.log('input command entered :' + event.which + ' ' + event.keyCode + ' ' + event.charCode);
}
else {
//console.log('input not number entered :' + event.which + ' ' + event.keyCode + ' ' + event.charCode);
event.preventDefault();
}
}
// input is not impty
if (this.validForm) {
// a number was typed
if (numberEntered) {
let newNumber = parseInt(this.numberVoucher + '' + String.fromCharCode(event.which));
console.log('new number : ' + newNumber);
// checking the condition of max value
if ((newNumber <= 30 && newNumber >= 1) || Number.isNaN(newNumber)) {
console.log('valid number : ' + newNumber);
}
else {
console.log('max value will not be valid');
event.preventDefault();
}
}
// command of delete or backspace was types
if (event.keyCode == 46 || event.which == 8) {
if (this.numberVoucher >= 1 && this.numberVoucher <= 9) {
console.log('min value will not be valid');
this.numberVoucher = 1;
//event.preventDefault();
this.validForm = true;
}
}
}
// input is empty
else {
console.log('this.validForm = true');
this.validForm = false;
}
};
in this function i had to just let the keypress of numbers, direction, deletes enter, so this function is just for the positive integer not doubles.
Firefox has supported patterns since 4.0
<input name="hours" type="number" pattern="[-+]?[0-9]*[.,]?[0-9]+"/>
(For help, see http://html5pattern.com/)

Resources