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

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>

Related

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

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;
});

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.

How to detect new empty line in textarea with Javascript?

I would like to detect a new empty line in a text area and if the user just pressed enter in the text area, without entering any data to return false and echo a message. I have made some research and thought of something like this:
var validatef ....
var code = (e.keyCode ? e.keyCode : e.which);
if (validatef == 'a value here' || code == 13) {
somevarhere.textcontent = 'Message';
return false;
}
else {....}
But it doesn't seem to work.
You can detect an empty line in a textarea by checking for the values:
\r\n (works fine for me) or \n
Just replace the text a value here with \r\n or \n what best suits you.
EDIT:
Check How to count string occurrence in string? to count regex appearances. So you can make a for loop to show the error message on /\s/g.
Hope it helps.
Try this
$('textarea').on('keypress', function(e) {
var val = $('textarea').val();
if (e.which == 13) {
if(! /\S/.test(val)) {
alert("no data");
}
}
});
this alerts no data for each keypress.
This is in jQuery but it will be similar even in plain Javascript
Here is the demo http://jsfiddle.net/TUCx8/
just test if the user pressed enter twice
/\n\n/.test(this.value)
According to the first sentence of the question, this may be one of possible solutions:
var enters = 0;
$('textarea').keypress(function(event) {
if (event.which == 13)
enters++;
else
enters = 0;
if (enters > 1) {
alert('You hit 2 new lines!');
}
});
Live example http://jsfiddle.net/fp6xk/
Another one solution is to check an empty line right before the end of text:
(function(){
$('textarea').keyup(function(event) {
if (/(\r?\n){2}$/.test($(this).val())) {
alert('2 consecutive empty lines at the end!');
}
});
})();
It would work independent of consecutive enter presses.
http://jsfiddle.net/fp6xk/4/

Remove only second character in jQuery

$('input').keypress(function(e){
if(($(this).val().split('a').length - 1) > 0){
console.log($('input').val());
$('input').val($('input').val().replace('a', ''));
}
})
jsfiddle: http://jsfiddle.net/Ht8rU/
I want have only one "a" in input. I check if length a > 1 and next remove "a" from input, but this not working good. I would like remove only second a from this input. One "a" is allow.
Edit: Oh I see now... If you want to keep only the first a you can try this:
$('input').keypress(function(e) {
var key = String.fromCharCode(e.which);
if (/a/i.test(key) && /a+/i.test(this.value)) {
e.preventDefault();
}
});
Demo: http://jsfiddle.net/elclanrs/Ht8rU/6/
You have to check if the current letter being typed is a:
if (String.fromCharCode(e.which) == 'a')
But here's a simplified version. You don't need to use val() if you can use value, specially because it makes your code cleaner. Also you might want to check for A or a so a regex might be a better option. Here's the code:
$('input').keypress(function(e) {
var A = /a/gi,
letter = String.fromCharCode(e.which);
if (A.test(letter)) {
$(this).val(this.value.replace(A,''));
}
});
Demo: http://jsfiddle.net/elclanrs/Ht8rU/3/
I suggest using preventDefault to stop the key from being pressed:
$('input').keypress(function(e) {
if (e.keyCode === 97 && $(this).val().split('a').length > 1) {
e.preventDefault();
}
});
JSFiddle
This code may seem long and without any usefulness, but it works.
$('input').keyup(function(e) {
var e = $(this),
val = e.val(),
aPos = val.indexOf('a'),
spl1 = val.substring(0, aPos + 1),
spl2 = val.substring(aPos, val.length).replace(/a/gi, ''),
v = spl1 + spl2;
e.val(v);
});
Here is a working JSFiddle of this.
I would try something like this. Not sure how well supported is the input event currently, though.
(function() {
var elem = $('input');
var value = elem.val();
elem.bind("input propertychange", function(e) {
if (elem.val().split('a').length - 1 > 1)
elem.val(value);
else
value = elem.val();
});
})();
http://jsfiddle.net/Ht8rU/8/
When the user presses 'a' or 'A', you can check if there is one 'a' or 'A' already present, if there is one already then you don't add it to the input.
$('input').keypress(function(e){
if ((e.keyCode === 65 || e.keyCode === 97) & $(this).val().match(/a/gi) !== null) e.preventDefault();
})
Updated jsFiddle
Here's a modified version of your fiddle that works: http://jsfiddle.net/orlenko/zmebS/2/
$('input').keypress(function(e){
var that = $(this);
var parts = that.val().split('a');
if (parts.length > 2) {
parts.splice(1, 0, 'a');
that.val(parts.join(''));
} else {
// no need to replace
}
})
Note that we only replace the contents of the input if we have to - otherwise, constant rewriting of the contents will make it impossible to type in the midle or at the beginning of the text.
If you want to further improve it and make it possible to type at the beginning even when we are replacing the contents, check out this question about detecting and restoring selection: How to get selected text/caret position of an input that doesn't have focus?

Get key value of a key pressed

I don't find how to get the value of a key pressed.
I currently have
$('#info_price').bind('keydown',function(evt){
alert(evt.keyCode);
but it return '49' when I press on 1 instead of returning '1'.
Edit: I'm aware that Ascii code of key '1'.
The final goal is to allow people to only write digit into the input. So i want to detect the non digit and not display them.
As it's told in comment it's ASCII code. To get it as character you can do:
alert(String.fromCharCode(evt.keyCode));
For those who google it now, like I am
$('input').on('keydown', function(e) {
console.log(e.key);
});​
Here is a fully done code for you to work with (not mine, but I used it):
http://www.selfcontained.us/2009/09/16/getting-keycode-values-in-javascript/
keycode = {
getKeyCode : function(e) {
var keycode = null;
if(window.event) {
keycode = window.event.keyCode;
}else if(e) {
keycode = e.which;
}
return keycode;
},
getKeyCodeValue : function(keyCode, shiftKey) {
shiftKey = shiftKey || false;
var value = null;
if(shiftKey === true) {
value = this.modifiedByShift[keyCode];
}else {
value = this.keyCodeMap[keyCode];
}
return value;
},
getValueByEvent : function(e) {
return this.getKeyCodeValue(this.getKeyCode(e), e.shiftKey);
},
keyCodeMap : {
8:"backspace", 9:"tab", 13:"return", 16:"shift", 17:"ctrl", 18:"alt", 19:"pausebreak", 20:"capslock", 27:"escape", 32:" ", 33:"pageup",
34:"pagedown", 35:"end", 36:"home", 37:"left", 38:"up", 39:"right", 40:"down", 43:"+", 44:"printscreen", 45:"insert", 46:"delete",
48:"0", 49:"1", 50:"2", 51:"3", 52:"4", 53:"5", 54:"6", 55:"7", 56:"8", 57:"9", 59:";",
61:"=", 65:"a", 66:"b", 67:"c", 68:"d", 69:"e", 70:"f", 71:"g", 72:"h", 73:"i", 74:"j", 75:"k", 76:"l",
77:"m", 78:"n", 79:"o", 80:"p", 81:"q", 82:"r", 83:"s", 84:"t", 85:"u", 86:"v", 87:"w", 88:"x", 89:"y", 90:"z",
96:"0", 97:"1", 98:"2", 99:"3", 100:"4", 101:"5", 102:"6", 103:"7", 104:"8", 105:"9",
106: "*", 107:"+", 109:"-", 110:".", 111: "/",
112:"f1", 113:"f2", 114:"f3", 115:"f4", 116:"f5", 117:"f6", 118:"f7", 119:"f8", 120:"f9", 121:"f10", 122:"f11", 123:"f12",
144:"numlock", 145:"scrolllock", 186:";", 187:"=", 188:",", 189:"-", 190:".", 191:"/", 192:"`", 219:"[", 220:"\\", 221:"]", 222:"'"
},
modifiedByShift : {
192:"~", 48:")", 49:"!", 50:"#", 51:"#", 52:"$", 53:"%", 54:"^", 55:"&", 56:"*", 57:"(", 109:"_", 61:"+",
219:"{", 221:"}", 220:"|", 59:":", 222:"\"", 188:"<", 189:">", 191:"?",
96:"insert", 97:"end", 98:"down", 99:"pagedown", 100:"left", 102:"right", 103:"home", 104:"up", 105:"pageup"
}
};
In javascript each key has associated with a ASCII code
as follows
1-49
2-50
like this
http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
So you need to map this values according to the keypress event.
The key code does not directly map to the character value. Instead, you need to look at the keypress event, which provides you with a charCode property. You can then use String.fromCharCode to turn that into a string.
You can detect all key values like this:
Here is working jsFiddle example.
$('textarea').keydown(function(e) {
var order = e.which;
console.log(order);
});​
Source.
To get the character of the ASCII:
String.fromCharCode();
to turn ASCII into a string.
Chrome and Opera today have Read only property data in event object.
It is written on MDN that currently this feature is "Working Draft".
https://developer.mozilla.org/en-US/docs/Web/API/InputEvent/data

Categories

Resources