I need to prevent the single and double quotes from being pasted in a text area in javascript
HTML
<textarea rows="10" cols="10" id="txtTest"></texarea>
Preventing the single and double quotes on keydown
$('#txtTest').on('keydown', function(e){
if(e.shiftKey && e.keyCode == 222 || e.keyCode == 222){
e.stopPropagation();
}
});
How to prevent the same when the text is pasted. (ctrl + v)
You'll need to trap more than the keydown event - Ctrl+V or right-click and paste can also insert characters (well and the older Shift+Insert). Depending on your usage, you may want to remove unwanted characters before submission. However, if you want it on the event, then trap all events and replace the text with the cleared text, depending on the event type.
$('#txtTest').val($('#txtTest').val().replace(/['"]/g, ''));
That'll remove all the single and double quotes (though not "smart" quotes).
may be this: http://jsfiddle.net/patelmilanb1/7NfLV/1/
$('#txtTest').on('keypress', function (e) {
var ingnore_key_codes = [34, 39];
if ($.inArray(e.which, ingnore_key_codes) >= 0) {
e.preventDefault();
}
});
listener to input event
var t = document.getElementById("text");
t.addEventListener("input", function (){
var str = this.value;
if (str.search(/'|"/g) !== -1) {
alert("\'\"is not allowed");
}
}, false);
demo: http://jsfiddle.net/EZXqH/
Besides coding the logic you have to think how to invoke the code at proper time. Here is a demonstration for that. On every system-paste event(either mouse or key board) the following code will run and do the operation. No need of any ASCII code.
Use the following:
$('textarea').on('paste', function () {
var element=$(this);
setTimeout(function () {
element.val(element.val().replace(/['"]/g, ""));
}, 1);
});
Check Fiddle
Related
I'm struggling to prevent input of alt + numpad unicode characters.
The alt key doesn't seem to register on keyup and will enter the unicode character regardless. (try something like 'alt + 1' in the example code snippet below to see what I mean.)
I've tried something like the following that attempts to restrict non-numeric characters:
$("#myInput").on('paste keyup keydown change', function(event) {
var $input = $(this);
var value = $input.val();
// remove whitespace
value = value.replace(/\s+/g, '');
// remove unwanted characters
value = value.replace(/[^0-9]+/g, '');
$input.val(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="myInput" type="text">
Is there an event I should be looking for instead of the above 4? (paste keyup keydown change)
I was able to prevent them on the keypress event...
function noteKeyPress(event) {
if(event.code.slice(0,3) == 'Alt'){
event.preventDefault();
event.stopPropagation();
}
}
This page was a great help
I've read all the answers on to this questions and none of the solutions seem to work.
Also, I am getting the vibe that triggering keypress with special characters does not work at all. Can someone verify who has done this?
If you want to trigger the keypress or keydown event then all you have to do is:
var e = jQuery.Event("keydown");
e.which = 50; // # Some key code value
$("input").trigger(e);
Slightly more concise now with jQuery 1.6+:
var e = jQuery.Event( 'keydown', { which: $.ui.keyCode.ENTER } );
$('input').trigger(e);
(If you're not using jQuery UI, sub in the appropriate keycode instead.)
The real answer has to include keyCode:
var e = jQuery.Event("keydown");
e.which = 50; // # Some key code value
e.keyCode = 50
$("input").trigger(e);
Even though jQuery's website says that which and keyCode are normalized they are very badly mistaken. It's always safest to do the standard cross-browser checks for e.which and e.keyCode and in this case just define both.
If you're using jQuery UI too, you can do like this:
var e = jQuery.Event("keypress");
e.keyCode = $.ui.keyCode.ENTER;
$("input").trigger(e);
I made it work with keyup.
$("#id input").trigger('keyup');
Ok, for me that work with this...
var e2key = function(e) {
if (!e) return '';
var event2key = {
'96':'0', '97':'1', '98':'2', '99':'3', '100':'4', '101':'5', '102':'6', '103':'7', '104':'8', '105':'9', // Chiffres clavier num
'48':'m0', '49':'m1', '50':'m2', '51':'m3', '52':'m4', '53':'m5', '54':'m6', '55':'m7', '56':'m8', '57':'m9', // Chiffres caracteres speciaux
'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', // Alphabet
'37':'left', '39':'right', '38':'up', '40':'down', '13':'enter', '27':'esc', '32':'space', '107':'+', '109':'-', '33':'pageUp', '34':'pageDown' // KEYCODES
};
return event2key[(e.which || e.keyCode)];
};
var page5Key = function(e, customKey) {
if (e) e.preventDefault();
switch(e2key(customKey || e)) {
case 'left': /*...*/ break;
case 'right': /*...*/ break;
}
};
$(document).bind('keyup', page5Key);
$(document).trigger('keyup', [{preventDefault:function(){},keyCode:37}]);
Of you want to do it in a single line you can use
$("input").trigger(jQuery.Event('keydown', { which: '1'.charCodeAt(0) }));
In case you need to take into account the current cursor and text selection...
This wasn't working for me for an AngularJS app on Chrome. As Nadia points out in the original comments, the character is never visible in the input field (at least, that was my experience). In addition, the previous solutions don't take into account the current text selection in the input field. I had to use a wonderful library jquery-selection.
I have a custom on-screen numeric keypad that fills in multiple input fields. I had to...
On focus, save the lastFocus.element
On blur, save the current text selection (start and stop)
var pos = element.selection('getPos')
lastFocus.pos = { start: pos.start, end: pos.end}
When a button on the my keypad is pressed:
lastFocus.element.selection( 'setPos', lastFocus.pos)
lastFocus.element.selection( 'replace', {text: myKeyPadChar, caret: 'end'})
console.log( String.fromCharCode(event.charCode) );
no need to map character i guess.
It can be accomplished like this docs
$('input').trigger("keydown", {which: 50});
I am using google virtual keybord and set on the textarea.
When I write something on textarea so in a textarea they print two character one was uppercase and second was lowercase.
I write a JavaScript function for textarea in which after "." - dot those character is make it automatically capital Alphabet.
How I can remove a one character and textarea print just only one character? Because when I press single key they print two character.
this function iam using for uppercase after the "." dot and set up keypress event on textarea.
function caps(e, textarea, value){
//debugger;
var unicode=e.keyCode? e.keyCode : e.charCode;
var str=value.trim();
str=str.charAt(str.length-1);
if((str=="." || value.length==0) && (unicode>=97 && unicode<=122)){
textarea.value=textarea.value+String.fromCharCode(unicode).toUpperCase();
return false;
}
return true;
}
To stop the default behaviour of an event, you can use e.preventDefault();. So something like
function caps(e, textarea, value){
//debugger;
var unicode=e.keyCode? e.keyCode : e.charCode; //my keyboard threw out ascii..
var str=value.trim();
str=str.charAt(str.length-1);
if(str=="." || value.length==0){
textarea.value=textarea.value+String.fromCharCode(unicode).toUpperCase();
e.preventDefault();
}
}
input.addEventListener("keypress",function(e){
if(e.keyCode==8) return true
caps(e,input,input.value)
},false)
You could use return false, but you need to do something like
input.onkeypress=function(){
if(e.keyCode==8) return true
return caps(e,input,input.value); //pass false from caps too event
}
Demo
If I understand correctly, it seems you just need to remove the last character before adding the new one. Therefore something like this should work (it's untested though).
if((str=="." || value.length==0) && (unicode>=97 && unicode<=122)){
/*remove last character before adding new one*/
textarea.value = textarea.value.substring(0, textarea.value.length - 1);
textarea.value=textarea.value+String.fromCharCode(unicode).toUpperCase();
return false;
}
Although, depending on how this function is being called, you may be able to prevent the character being printed in the first place.
Sorry, realised you did say in the question title that it's the keypress event. In which case, e.preventDefault is your friend as shown in another answer. You can just replace your return false with it.
When non-printable char is pressed, it's replaced with let's say for CTRL=17 with "[CTRL]".
Here is code an example
$('#textbox1').keyup(function (event) {
if (8 != event.keyCode) {
if(17==event.keyCode){
$('#textbox1').val($('#textbox1').val()+"[CTRL]")
$('#textbox2').val($('#textbox1').val());
}else{
$('#textbox2').val($('#textbox1').val());
}
} else {
$('#textbox2').val($('#textbox1').val());
}
});
the problem is when user presses backspace the second input must reflect the content of the first one, so "[CTRL]" must be deleted at once like any other chars.
You could make use of the keyCode and/or in combination with charCode (if required). Basic idea would be:
Create a map of all required key codes in an array/object
Handle event for say keydown and listen for keycode
Look for the keycode in your map and if found show it
prevent the default (to prevent e.g. say backspace browsing back)
If not found in map, let the character go thru as usual.
A very basic example:
Demo: http://jsfiddle.net/abhitalks/L7nhZ/
Relevant js:
keyMap = {8:"[Backspace]",9:"[Tab]",13:"[Enter]",16:"[Shift]",17:"[Ctrl]",18:"[Alt]",19:"[Break]",20:"[Caps Lock]",27:"[Esc]",32:"[Space]",33:"[Page Up]",34:"[Page Down]",35:"[End]",36:"[Home]",37:"[Left]",38:"[Up]",39:"[Right]",40:"[Down]",45:"[Insert]",46:"[Delete]"};
$("#txt").on("keydown", function(e) {
// check if the keycode is in the map that what you want
if (typeof(keyMap[e.keyCode]) !== 'undefined') {
// if found add the corresponding description to the existing text
this.value += keyMap[e.keyCode];
// prevent the default behavior
e.preventDefault();
}
// if not found, let the entered character go thru as is
});
Edit: (as per the comments)
The concept remains the same, just copying the value to the second input:
Demo 2: http://jsfiddle.net/abhitalks/L7nhZ/3/
$("#txt1").on("keyup", function(e) {
if (typeof(keyMap[e.keyCode]) !== 'undefined') {
this.value += keyMap[e.keyCode];
e.preventDefault();
}
$("#txt2").val(this.value); // copy the value to the second input
});
Regarding deletion of the description, I could not get it done by caching the last inserted descrition from the map. Somehow, I kept struggling with the regex with a variable. Anyway, a simpler solution is to just add another event handler for keyup with hard-coded map.
Thanks to #serakfalcon for (that simple solution), which we are using here:
$('#txt1').keydown(function(event) {
if(8 == event.keyCode) {
var el = $(this);
el.val(el.val().replace(/\[(Tab|Enter|Shift|Ctrl|Alt|Break|Caps Lock|Esc|Space|Page (Up|Down)|End|Home|Left|Up|Right|Down|Insert|Delete)\]$/,' '));
$("#txt2").val(el.val());
}
});
You can check in the keydown for the last character in the input field. If it's a ] you can remove everything from the right to the last found opening bracket [. Unfortunatly this does not work if you're cursor is inside '[ ]'.
$('#textbox1').keydown(function(event) {
if(8 == event.keyCode) {
var element = $(this),
value = element.val(),
lastChar = value.slice(-1);
if(lastChar == ']') {
var lastIndex = value.lastIndexOf('['),
index = value.length - lastIndex;
element.val(value.slice(0, -index) + "]");
}
}
});
Fiddle
you can always use a regex.
$('#textbox1').keydown(function(event) {
if(8 == event.keyCode) {
var el = $(this);
el.val(el.val().replace(/\[(CTRL|ALT|SHIFT)\]$/,' '));
}
});
fiddle
Edit: combined with abhitalks code
I'm attempting to do info validation against user text input in the process of keydown event. The reason that I am trying to validate in the keydown event is because I do not want to display the characters those that are considered to be illegal in the input box at the beginning.
The validation I am writing is like this,
function validateUserInput(){
var code = this.event.keyCode;
if ((code<48||code>57) // numerical
&&code!==46 //delete
&&code!==8 //back space
&&code!==37 // <- arrow
&&code!==39) // -> arrow
{
this.event.preventDefault();
}
}
I can keep going like this, however I am seeing drawbacks on this implementation. Those are, for example:
Conditional statement become longer and longer when I put more conditions to be examined.
keyCodes can be different by browsers.
I have to not only check what is not legal but also have to check what are exceptional. In above examples, delete, backspace, and arrow keys are exceptional.
But the feature that I don't want to lose is having not to display the input in the textarea unless it passes the validation. (In case the user try to put illegal characters in the textarea, nothing should appear at all) That is why I am not doing validation upon keyup event.
So my question is:
Are there better ways to validate input in keydown event than checking keyCode by keyCode?
Are there other ways to capture the user inputs other than keydown event before browser displays it? And a way to put the validation on it?
If you're checking a printable key, which is exactly what you seem to be doing, you should use the keypress event instead, since that's the only place you're going to be able to get reliable information about the character the keypress represents. You can't detect numeric keypresses reliably in the keydown event. Also, it's a bad idea to suppress arrow keys and delete/backspace keys. What do you gain from doing that?
There's also some errors: in Firefox, you'll need to get the Event object from the parameter passed into the event handler function, and if you're using a DOM0 event handler function rather than addEventListener() or attachEvent(), you should use return false; to suppress default behaviour. Here's my recommended code:
var input = document.getElementById("your_input_id");
input.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
if (/\d/.test(charStr)) {
return false;
}
};
I don't think you need the preventDefault part. If you want to catch keys (by event.keyCode, or combinations using for example event.ctrlKey + event.keyCode), you check if the keyCode is allowed. If it is, simply return true, otherwise return false. If you return false, the key input will not be written to the input field, otherwise it will.
I can't think of better ways to then using keyCode. You can use String.fromCharCode([keyCode]) if you want to check for specific character values, but it keeps boiling down to some loop to check the keyCodes you want to validate. May be a switch ... case could offer a bit more readability.
Here's a piece of code from a keydown event handler I use (just for demonstration, it doesn't actually do anything):
function handleKey(e, thisFld) {
thisFld = (thisFld || this);
e = e || event;
if (!e) {
return true;
}
var isCtrl = e.ctrlKey,
isShift = e.shiftKey,
isAlt = e.altKey,
kc = e.keyCode || e.which,
codes = [27, 38, 40],
keys = {
escape: 27,
up: 38,
down: 40,
ins: 45,
del: 46,
one: 49
};
if (isCtrl && kc === keys.del) { ... }
if (isAlt && kc === keys.ins) { ... }
//etc
return true;
}
here's a fiddle that you can play with and may provide more insight.
jsfiddle: keydown/keypress demo w/ info display
It would appear that the latest browsers use preventDefault(). The code below is similar to what i put on jsfiddle but is standalone and can be pasted into an html file that you can access locally to test (note it's mobile friendly for device testing.
<html>
<head>
<meta name="viewport" content="initial-scale=1, minimum-scale=1, maximum-scale=1, width=device-width, user-scalable=no"/>
<style>
.b {color:blue;}
.r {color:red;}
input {font-size:18px;}
</style>
<script>
function byId(el) {return document.getElementById(el)}
function sfcc (n) {return String.fromCharCode(n);}
function foo(event) {
var he='&#x'+event.keyIdentifier.split('+')[1]+';';
var html=''
var cn=event.target.className;
html+='kc: [<span class="b">'+sfcc(event.keyCode)+'</span>] ';
html+='wh: [<span class="b">'+sfcc(event.which)+'</span>] ';
html+='he: [<span class="b">'+he+'</span>]<br>';
for (i in event)
if (["string","boolean","number"].indexOf(typeof event[i]) >-1 && i.toUpperCase()!=i)
html+='<span>'+i + '</span>: [<span class="r">'+event[i]+'</span>]<br>';
byId('kc').innerHTML=html;
switch (cn) {
case "pd": event.preventDefault(); return;
case "rf": return false;
}
}
</script>
</head>
<body>
kp/pd: <input class="pd" type="text" onkeypress="foo(event)"/><br>
kp/rf: <input class="rf" type="text" onkeypress="foo(event)"/><br>
kd/pd: <input class="pd" type="text" onkeydown="foo(event)"/><br>
kd/rf: <input class="rf" type="text" onkeydown="foo(event)"/><br>
<div id="kc"></div>
</body>
</html>
So, I've found that keypress is great for printable characters, and keydown for all the rest. You can check the event.charCode on keypress for printable characters (it should be 0 for non-printable).
You can use event.keyCode on keydown for arrows and such.
This is how I just got an autocomplete to work in Chrome and Firefox.