I have a text area which should accept only selected characters - javascript

The text area should accept only numbers, comma, arrow keys (keyboard), space, Ctrl+c, Ctrl+v, Ctrl+x, Ctrl+a and it should be in javascript only.
Following is my code :
<textarea onkeypress=' return validateKey(event)'></textarea>
<body>
<script type="text/javascript">
function validateKey(e){
var key= e.keyCode ? e.keyCode : e.charCode;
console.log(key);
if(key>47 && key <=57 || key>36 && key <=40 || key===44|| key===32 ||x|| key===8 || x|| key ===118 || key==99 || key === 120){
return true;
}
return false;
}
</script>
</body>
it works fine with chrome but in firefox, it takes the same keycode for 'a' and ctrl+a or cmd+a (mac) and so on for cut, paste, copy.
Is there any way in which i can treat ctrl+a and 'a' are two diff characters.

Just add a if (!e.ctrlKey) outside your other if. This will prevent it from running if the control key is being pressed.

I have found the way for this validation
<!DOCTYPE html>
<html>
<head>
<title>Task</title>
</head>
<body>
<textarea style="width: 300px;height: 100px" onkeypress=' return validateKey(event)'></textarea>
<script type="text/javascript">
function validateKey(e) {
var key = e.keyCode ? e.keyCode : e.charCode;
console.log(key);
if (key > 47 && key <= 57||(key > 36 && key <= 40) && !e.shiftKey || key === 44 || key == 17 || key === 32 || key === 8 || (key == 97 && e.ctrlKey) || (key == 120 && e.ctrlKey) || (key == 99 && e.ctrlKey) || (key == 118 && e.ctrlKey) || e.metaKey) {
return true;
}
return false;
}
</script>
</body>
</html>

Related

When pasteing value into input area, can't capture value

I have a button and an input area. When the input's length is filled (14) - then the button's class will be active. That currently works, however, when the user pastes a value into the input area, the length is zero until the user enters something else. My goal is to display the active class on the button when the paste is done if the length of the value is 14.
JS
$('#number', '#form')
.keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
$phone = $(this);
$len = $phone.val().length;
console.log($len);
// Auto-format
if (key !== 8 && key !== 9) {
if ($phone.val().length === 13){
$('#form div a:eq(0)').removeClass('inactive');
}
if (($phone.val().length === 14) && (key == 13)){
e.preventDefault();
$('#form div a:eq(0)').trigger('click');
}
if ($phone.val().length < 13){
$('#form div a:eq(0)').addClass('inactive');
}
}
if (key == 8){
$('#form div a:eq(0)').addClass('inactive');
}
// Allow numeric, tab, backspace, delete, and arrow keys only
return (
key == 8 ||
key == 9 ||
key == 46 ||
key == 86 || //copy+paste
key == 67 ||
key == 17 ||
key == 91 || // end
(key >= 37 && key <= 40)||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105)
);
});
document.getElementById('number').addEventListener('input', function (e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
});
HTML
<form id="form">
<input id="number" type="text" maxlength="14" placeholder='(100) 100-1000'>
<div>
<a class='bt inactive'>Enter</a>
</div>
</form>
You should use the input event. This event is triggered when eve the input changes. keyup and keydown will fire even if the input hasn't changed. Pressing CTRL will trigger keydown even if nothing has changed. input will only be triggered if it has changed, ie: CTRL + V (paste)
$('#number', '#form')
.on('input', function (e) {
var key = e.charCode || e.keyCode || 0;
$phone = $(this);
$len = $phone.val().length;
console.log($len);
// Auto-format
if (key !== 8 && key !== 9) {
if ($phone.val().length === 13){
$('#form div a:eq(0)').removeClass('inactive');
}
if (($phone.val().length === 14) && (key == 13)){
e.preventDefault();
$('#form div a:eq(0)').trigger('click');
}
if ($phone.val().length < 13){
$('#form div a:eq(0)').addClass('inactive');
}
}
if (key == 8){
$('#form div a:eq(0)').addClass('inactive');
}
// Allow numeric, tab, backspace, delete, and arrow keys only
return (
key == 8 ||
key == 9 ||
key == 46 ||
key == 86 || //copy+paste
key == 67 ||
key == 17 ||
key == 91 || // end
(key >= 37 && key <= 40)||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105)
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
<input id="number" type="text" maxlength="14" placeholder='(100) 100-1000'>
<div>
<a class='bt inactive'>Enter</a>
</div>
</form>
Also use another event input so it triggers your function on keydown and on input as well. Check out this working example using your code
$('#number', '#form').on('keydown input',function(){});
$('#number', '#form')
.on('keydown input', function (e) {
var key = e.charCode || e.keyCode || 0;
$phone = $(this);
$len = $phone.val().length;
console.log($len);
// Auto-format
if (key !== 8 && key !== 9) {
if ($phone.val().length === 13){
$('#form div a:eq(0)').removeClass('inactive');
}
if (($phone.val().length === 14) && (key == 13)){
e.preventDefault();
$('#form div a:eq(0)').trigger('click');
}
if ($phone.val().length < 13){
$('#form div a:eq(0)').addClass('inactive');
}
}
if (key == 8){
$('#form div a:eq(0)').addClass('inactive');
}
// Allow numeric, tab, backspace, delete, and arrow keys only
return (
key == 8 ||
key == 9 ||
key == 46 ||
key == 86 || //copy+paste
key == 67 ||
key == 17 ||
key == 91 || // end
(key >= 37 && key <= 40)||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105)
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
<input id="number" type="text" maxlength="14" placeholder='(100) 100-1000'><br /><br />
<div>
<a class='bt inactive'>Enter</a>
</div>
</form>

Need help restricting a js function(that restricts invalid chars) to a particular input type

Hi i would like to restrict a function that allows only, numbers, back space and left & right arrow keys to inputs with number type, because when i implement it, it also affects my text inputs.
<script>
function chars(evt){
var key = window.event ? event.keyCode : event.which;
if (event.keyCode == 8 || event.keyCode == 46
|| event.keyCode == 37 || event.keyCode == 39) {
return true;
}
else if ( key < 48 || key > 57 ) {
return false;
}
else return true;
}
</script>
Assign an id to your <input>. Add an event listener to it, like :
function getKeyCode() {
var key = window.event ? event.keyCode : event.which;
if(event.keyCode == 8 || event.keyCode == 46
|| event.keyCode == 37 || event.keyCode == 39) {
console.log(true);
//return true;
} else if (key < 48 || key > 57) {
console.log(false);
// return false;
} else {
console.log(true);
// return true;
}
}
var el = document.getElementById("myInput");
el.addEventListener("keypress", getKeyCode);
<input type="text" id="myInput">

jQuery detect keyboard press then focus to textbox

I have jQuery function that detect if some key in keyboard pressed. So far that worked, example if I press "P" then it will focus to textbox.
$(document).keyup(function(e)
{
if (e.keyCode == 51 || e.keyCode == 52 || e.keyCode == 80 || e.keyCode == 65)
{
$("#code_read_box").focus();
}
});
Now I want when I press "P", "P" will set too to textbox.
<input type="text" id="code_read_box" value=""/>
Any advice ?
DEMO here
Use String.fromCharCode:
String.fromCharCode(e.keyCode)
Demo: http://jsfiddle.net/hw2g5/
Your code:
$(document).keyup(function(e) {
if (e.keyCode == 51 || e.keyCode == 52 || e.keyCode == 80 || e.keyCode == 65) {
$("#code_read_box").focus();
$("#code_read_box").val(String.fromCharCode(e.keyCode));
}
});
If you want to append values, so:
$("#code_read_box").val($("#code_read_box").val() + String.fromCharCode(e.keyCode));
Solved.
$(document).keyup(function(e) {
var key = String.fromCharCode(e.keyCode);
if (key.match(/[34PA]/) && !$('input').is(':focus')) {
$('input').focus();
$('input').val($('input').val() + key);
}
});

How the DEL Key with Mozilla Firefox

I need the help for my problem in my asp.net MVC3 application I have a textbox which is validating for currency format ($228.00) but in this text box it doesn't work for the DEL key because . and delete key have same ASCII key which 46. I also set a validation in this textbox for . is only one time will be accept in the text box so if "." entered one time then delete will not work.
Here is my validate Javascript:
function validateForCharacter(val, id, e) {
window.event.keyCode : -1;
var key = e.keyCode || e.charCode || e.which;
var currentChar = String.fromCharCode(key);
if (val.indexOf(currentChar) != -1 && currentChar == ".")
{
return false;
}
if (key >= 48 && key <= 57 || key == 46 || e.keyCode === 8 || e.keyCode === 9 || e.keyCode === 37 || e.keyCode === 35 || e.keyCode === 39)
{
$(this).val("");
return true;
}
return false;
}
This is my View (Html) code for textbox:
<input type="text" id="t1" onkeypress="return validateForCharacter(value, id, event)/>
Jquery does it right... but in case you need specifically detect delete key on Firefox or IE9 you can use event.key property.
I.E:
if (event.key == "Delete")
Live Demo:
$(document).ready(function() {
$("#nondeletable").on("keydown", function(event) {
$("#result").html(event.type + ": " + event.which);
if (event.key == "Delete")
$("#result").append(" <b>Delete!</b>");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="nondeletable" />
<div id="result"></div>

javascript : key validation

im using javascript to validate keys in textbox. it is not working :(
function numeric(e) {
return ((e.keyCode == 8) ||
(e.keyCode == 9) ||
(e.keyCode > 47 && e.keyCode < 58) ||
(e.keyCode > 36 && e.keyCode < 41) ||
(e.keyCode == 46) ||
(e.keyCode > 95 && e.keyCode < 106) ||
e.keyCode == 190 ||
e.keyCode == 110);
}
help me...
function numeric(e) {
e = e || window.event;
keycode = e.keyCode || e.which;
if(keycode === 13){
alert("cheese");
}
}
I know that in I.E. you can set event.keyCode=0 to suppress the key appearing in the control. But I think you need to trap the onkeydown. Firefox might have an equivalent. This is good because it prevents the key actually "arriving" at the control.
Also keep in mind that you might need to handle combinations of Shift + key and alt + key.
a good debug technique for this sort of thing is to say windows.status = event.keyCode,
and you can see what the keycode is as you type it...
Just try out the following code. I have checked F5 keycode, you can check as you want
function disableKey(event)
{
if (!event) event = window.event;
if (!event) return;
var keyCode = event.keyCode ? event.keyCode : event.charCode;
if (keyCode == 116) {
showMsg("This functionality is disabled.");
window.status = "F5 key detected! Attempting to disabling default response.";
window.setTimeout("window.status='';", 2000);
// Standard DOM (Mozilla):
if (event.preventDefault) event.preventDefault();
//IE (exclude Opera with !event.preventDefault):
if (document.all && event && !event.preventDefault) {
event.cancelBubble = true;
event.returnValue = false;
event.keyCode = 0;
}
return false;
}
}
function setEventListenerForFrame(eventListener)
{
document.getElementById('your_textbox').onkeydown = eventListener;
//frames['frame'].document.onkeypress = eventListener;
}
<body onload="setEventListener(disableKey);">
Try this if you want a numbers only textbox:
function numbercheck(event) {
var unicode = event.charCode; var unicode1 = event.keyCode; if (navigator.userAgent.indexOf("Firefox") != -1 || navigator.userAgent.indexOf("Safari") != -1) {
if (unicode1 != 8) {
if ((unicode >= 48 && unicode <= 57) || unicode1 == 37 || unicode1 == 39 || unicode1 == 35 || unicode1 == 36 || unicode1 == 9 || unicode1 == 46)
{ return true; }
else
{ return false; }
}
}
if (navigator.userAgent.indexOf("MSIE") != -1 || navigator.userAgent.indexOf("Opera") == -1) {
if (unicode1 != 8) {
if (unicode1 >= 48 && unicode1 <= 57)
{ return true; }
else
{ return false; }
}
}
}
And in your textbox call it on the onkeypress event:
onkeypress="return numbercheck(event)"

Categories

Resources