JavaScript how to make backspace work in my keyCode text prompt? - javascript

I'm creating a way to type anywhere by intercepting the keydown event instead of using a text box for a project. I'm having trouble finding out how to implement the backspace. This is a shortened version of my code:
$(document).keydown(function(event){
typed = String.fromCharCode(event.keyCode);
display += typed;
document.getElementById("text").innerHTML = letterContainer;
});
I was trying to use the .replace function like this...
if (event.keyCode == 8) {
display.replace(typed,'');
}
...and put it at the beginning, but that doesn't work. Any ideas?

You're getting there. How are you emptying the text in the input tag?
if (event.keyCode == 8) {
display.replace(typed,'');
// ^ This does not change the value of the <input>
}
I'd suggest something like:
function isDeleteKeyCode(event) {
return event && event.keyCode === 8;
}
function resetValue(element) {
element.value = '';
}
$('#input-id').keydown(function(event) {
if (isDeleteKeyCode(event)) {
resetValue(event.target);
}
// ^ This can be simplified as: isDeleteKeyCode(event) && resetValue(event.target)
});
That would add a keydown listener to an input tag with id="input-id".
Demo: https://jsfiddle.net/pp16tru7/

var display = '';
$(document).keydown(function(event) {
var typed = String.fromCharCode(event.keyCode);
// if backspace, get text without the last character, else add character to display
if (event.keyCode === 8) {
display = display.substr(0, display.length - 1);
} else {
display += typed;
}
document.getElementById("text").innerHTML = display;
});

Related

Shift tab not retaining the element focus

Javascript version code -- Link
if (el.value.length > 1) {
el.value = el.value[el.value.length - 1];
}
try {
if (el.value == null || el.value == "") {
this.foucusOnInput(el.previousElementSibling);
} else {
this.foucusOnInput(el.nextElementSibling);
}
} catch (e) {
console.log(e);
}
AngularJS version code - Link
if (ele.currentTarget.value.length >= 1) {
ele.currentTarget.value = ele.currentTarget.value[ele.currentTarget.value.length - 1];
}
try {
if (ele.currentTarget.value === null || ele.currentTarget.value === "") {
foucusOnInput(ele.currentTarget.previousElementSibling);
} else {
foucusOnInput(ele.currentTarget.nextElementSibling);
}
} catch (e) {
console.log(e);
}
Not able to implement the javascript version of
Tab & Shift+Tab
functionality in AngularJS. Let me know what am missing here!
Requirement - Once you enter the value to the input text the next input text element should be focused; On Shift-Tab previous input text element should be focused.
The keyup event gets triggered for every key up including tab and shift. This is the difference between your javascript solution angularjs solution.
I'm not sure if there is an equivalent to oninput in angularjs. 'keyup', 'keydown', 'input' all work differently. There is ng-change in angularjs but it requires ng-model on the input element and I don't think $event works with ng-change.
Anyway, there is a working solution. Try this:
$scope.readKey = function(ele) {
console.log(ele);
if(ele.shiftKey) return;
if (ele.currentTarget.value.length >= 1) {
ele.currentTarget.value = ele.currentTarget.value[ele.currentTarget.value.length - 1];
}
try {
if (ele.currentTarget.value === null || ele.currentTarget.value === "" ) {
foucusOnInput(ele.currentTarget.previousElementSibling);
} else {
foucusOnInput(ele.currentTarget.nextElementSibling);
}
} catch (e) {
console.log(e);
}
};
This code, as listened on keyup instead of input, will not allow to go to next input field if current input field is empty. In your javascript example, the code in input handler never gets executed and so you can move to next input field if current one is empty.
If you want to achieve the same thing in angularjs solution as well, then try changing the condition to this:
if(ele.shiftKey || ele.keyCode === 9) return;
This prevents the code from getting executed if its shift key or tab key. 9 is the keycode for TAB.
Working solution -- Link
if(ele.key != "Tab" && ele.key != "Shift" ){
if (ele.currentTarget.value.length >= 1) {
ele.currentTarget.value = ele.currentTarget.value[ele.currentTarget.value.length - 1];
}
try {
if (ele.currentTarget.value === null || ele.currentTarget.value === "") {
foucusOnInput(ele.currentTarget.previousElementSibling);
} else {
foucusOnInput(ele.currentTarget.nextElementSibling);
}
} catch (e) {
console.log(e);
}
}

jQuery: selectionStart returns undefined

Situation
browser
Google Chtome 69
html
<textarea id="message" name="message">
// input some messsage
</textarea>
js(jQuery)
$(function () {
$("#message").on("keydown keyup keypress change", function () {
//this part runs correctly
})
$('#message').on('keydown', function (e) {
if ((e.wich && e.wich === 13) || (e.keyCode && e.keyCode === 13)) {
var $textarea = $(this);
var sentence = $textarea.val();
var position = $textarea.selectionStart;
var length = sentence.length;
var before = sentence.substr(0, position);
var after = sentence.substr(position, length);
sentence = before + "\n" + after;
}
});
});
When I input something in the #message textarea and push Enter key in the area, nothing would happen. According to Chrome developer tool, selectionStart method seems to return Undefined.
Needs
Enter key has been made disabled in this form page in order to avoid submitting the data mitakenly.
js
function fnCancelEnter()
{
if (gCssUA.indexOf("WIN") != -1 && gCssUA.indexOf("MSIE") != -1) {
if (window.event.keyCode == 13)
{
return false;
}
}
return true;
}
However, in this textarea, I want to enable user to add a break line by pressing Enter key.
I'm sorry but I don't have much knowledge about jQuery and javascript. Please tell me how to do.
Please replace $textarea.selectionStart by $textarea.get(0).selectionStart. Then try again.

Jquery: An alternate method for fromcharcode() to convert integer to character

I'm coding a chat box. And the Characters that I enter, is not reflected as it is.
This is basically the code I'm using.
$(document).ready(function() {
$(".entry").keydown(function(event) {
console.log(String.fromCharCode(event.which));
});
});
And so when I type (lower-case) "a", console tab shows me "A".
special characters will not get reflected unless I create separate condition for it.
Could someone help me with a different function which does it all by itself, and returns a string as entered by the user. Or a different approach to this challenge all together. Thanks.
Actual code - chat.js
var str='';
$(document).ready(function() {
$(".entry").keydown(function(event) {
console.log(event.which);
if (event.which === 13 && event.shiftKey === false) {
console.log(str);
event.preventDefault();
} else {
var c = event.which;
str = str.concat(String.fromCharCode(c));
}
});
});
So basically the every character entered would get concated to the string. and Enter key would dump the text to console.
It's seems that trying to get the value of event.which in keydown event could lead you to a wrong ascii code (What you need to pass to String.fromCharCode).
See https://stackoverflow.com/a/10192144/3879872
I don't know if it fits your needs, but you could try:
$(document).ready(function(){
$(".entry").keypress(function(event) {
console.log(String.fromCharCode(event.which));
});
});
(Note the use of keypress instead of keydown)
EDIT: Added working Demo
var str = '';
$(document).ready(function() {
$(".entry").keypress(function(event) {
console.log(event.which);
if (event.which === 13 && event.shiftKey === false) {
console.log(str);
event.preventDefault();
} else {
var c = event.which;
str = str.concat(String.fromCharCode(event.which));
}
console.log('Formated Text', str);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="entry"></textarea>

CKEditor no space on buttons

I'm using the CKEDITOR.inline(element) feature of CKEditor (contenteditable=true) in a "WYSIWYG" content editor that I'm working on. The thing works great for all kinds of tags that I've tested with except on:
When I go to edit a <button>, I can edit the text inside of the tag, just fine, except for "space".
When I hit the spacebar, instead of getting a space character inserted in the text, the button attempts to be "pressed", since, I'm assuming the default functionality of the browser is to try and "press" a button that is focused.
So.. I tried to "highjack" the $(element).on('keydown') event and checked for keycode 32 to apply preventDefault to the event. That technically worked to do the "highjacking" (I can see the below console.log), but I still don't get a "space" in the content.
var _fixButtonSpaceKeydown = function(elem, removeBinding){
console.log("_fixButtonSpaceKeydown()");
if(removeBinding){
jQuery(elem).off('keydown');
} else {
jQuery(elem).on('keydown', function (e) {
if (e.keyCode == 32) {
console.log('Caught space!');
e.preventDefault();
}
});
}
}
Has anyone come across this w/ CKEditor before, and have they found a solution?
Below workaround won't stop onclick() on Chrome while focusing on a button and type space. This is a browser issue and it seems there's no way to totally prevent the event. Anyway, we can still add space(Make sure to insert HTML encoding) at the cursor position:
jQuery(contentEditableBtn).attr('onclick','event.preventDefault(); insertSpace();');
function insertSpace(){
var range, node;
if (window.getSelection && window.getSelection().getRangeAt) {
range = window.getSelection().getRangeAt(0);
node = range.createContextualFragment(" ");
range.insertNode(node);
window.getSelection().collapseToEnd();
window.getSelection().modify("move", "forward", "character");
} else if (document.selection && document.selection.createRange) {
document.selection.createRange().pasteHTML(" ");
document.selection.collapseToEnd();
document.selection.modify("move", "forward", "character");
};
}
Maybe you could manually insert a space after preventDefault(). I'm not sure if this would work, but it's worth a try:
var _fixButtonSpaceKeydown = function(elem, removeBinding){
console.log("_fixButtonSpaceKeydown()");
if(removeBinding){
jQuery(elem).off('keydown');
} else {
jQuery(elem).on('keydown', function (e) {
if (e.keyCode == 32) {
console.log('Caught space!');
e.preventDefault();
e.target.innerHTML += ' ';
}
});
}
}
Try this: I haven't tested it but I'm sure you can add space by getting the cursor position where a char is then add a space before the char and replace the paragraph.
Something like this:
var _fixButtonSpaceKeydown = function(elem, removeBinding){
console.log("_fixButtonSpaceKeydown()");
if(removeBinding){
jQuery(elem).off('keydown');
} else {
jQuery(elem).on('keydown', function (e) {
var p = "";
if (e.keyCode == 32) {
console.log('Caught space!');
e.preventDefault();
p = e.target.innerHTML;
// get position of cursor
var cursorPosition = window.getSelection().getRangeAt(0).startOffset;
p.replace(p.charAt(position), " " + p.charAt(position));
// replace the content after change
e.target.innerHTML = p;
}
});
}
}

How to replace code to use RegExp

I have the following code which checks for "enter" key as well as prevent the use of > and < sign in the textbox.
<script type="text/javascript" language="javascript">
function checkKeycode(e) {
var keycode;
if (window.event) // IE
keycode = e.keyCode;
else if (e.which) // Netscape/Firefox/Opera
keycode = e.which;
if (keycode == 13) {
//Get the button the user wants to have clicked
var btn = document.getElementById(btnSearch);
if (btn != null) { //If we find the button click it
btn.click();
event.keyCode = 0
}
//Removed when above code was added 12-09-13
//CallSearch();
}
}
function CallSearch() {
var objsearchText = window.document.getElementById('txtSearchText');
var searchText;
if ((objsearchText!=null))
{
searchText = objsearchText.value;
searchText = searchText.replace(/>/gi, " >");
searchText = searchText.replace(/</gi, "< ");
objsearchText.value = searchText;
}
//This cookie is used for the backbutton to work in search on postback
//This cookie must be cleared to prevent old search results from displayed
document.cookie='postbackcookie=';
document.location.href="search_results.aspx?searchtext=";
}
</script>
How can I shorten the code to be more effecient and use the onBlur function and to use RegExp instead of replace? Or is replace a faster method than RegExp?
You are saying that you want to prevent < and > chars. Here is an easier way, just ignore these chars when the keydown event occurs on them.
Also I suggest to use jQuery - if you can.
http://api.jquery.com/event.which/
var ignoredChars = [188, 190]; // <, >
$('#myTextField').keydown(function(e) {
if(ignoredChars.indexOf(e.which) > -1) {
e.preventDefault();
e.stopPropagation();
return false;
}
})
.keyup(function(e) {
if(e.which === 13) {
$('#searchButton').click();
}
});
Just add this event handler to your textbox and remove the regexp replacements.
If you don't want characters to be input by user, surpress them as early as possible. This way you won't get in trouble fiddling them out of a big string later.

Categories

Resources