This way works but it strikes me as working too hard.
Question: How do you determine which key has been pressed?
;(function() {
var Variables = {}
Variables.slash = false
$('[name=myName]').keypress(keypress)
function keypress(myEvent) {
if (myEvent.which === 47) {
Variables.slash = true
}
}
$('[name=myName]').keyup(keyup)
function keyup(myEvent) {
if (Variables.slash) {
Variables.slash = false
}
}
})()
It can be simplified, by following steps:
You need to find out the ASCII code of the key pressed (https://api.jquery.com/event.which/)
Now just use a ASCII reference table and find out which char was pressed.
The myEvent variable will contain the ASCII code of the key that have been pressed.
The ASCII code of slash is 47. (See here)
From a previous question:
"Clear" JavaScript:
<script type="text/javascript">
function myKeyPress(e){
var keynum;
if(window.event){ // IE
keynum = e.keyCode;
}
else if(e.which){ // Netscape/Firefox/Opera
keynum = e.which;
}
alert(String.fromCharCode(keynum));
}
</script>
<form>
<input type="text" onkeypress="return myKeyPress(event)" />
</form>
JQuery:
$(document).keypress(function(event){
alert(String.fromCharCode(event.which));
})
Related
I have the following below function which disables to enter numbers or special characters in the text box. This function are working fine in IE and Chrome, but in the firefox these are not working and am able to enter the numbers and characters. Can anyone please suggest how this can be resolved in firefox? My FF version is 57.0.4
$("#firstName").keypress(function(event) {
var character = String.fromCharCode(event.keyCode);
return isValid(character);
});
function isValid(str) {
return !/[~`!##$%\^&*()+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
$( document ).ready(function() {
$( "#firstName" ).keypress(function(e) {
var key = e.keyCode;
if (key >= 48 && key <= 57) {
e.preventDefault();
}
});
keyCode is deprecated. jQuery normalizes this property for cross browser usage in the event.which property.
$("#firstName").keypress(function(event) {
var character = String.fromCharCode(event.which);
return isValid(character);
});
function isValid(str) {
return !/[~`!##$%\^&*()+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
$("#firstName").keypress(function(e) {
var key = e.which;
if (key >= 48 && key <= 57) {
e.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id=firstName />
To disables to enter numbers or special characters you can use
/[~`!##$%\^&*+=\-\[\]\\';,_./{}\(\)\|\\":<>\d+$?]/g
You can try this regex Here And instead of using keypress() you can use .on('input') .. The next code works for me in chrome , firefox and IE
$("#firstName").on( 'input' ,function(event) {
var ThisVal = $(this).val();
if(isValid(ThisVal) == false){
$(this).val(ThisVal.substr(0, ThisVal.length - 1));
}
});
function isValid(str) {
return !/[~`!##$%\^&*+=\-\[\]\\';,_./{}\(\)\|\\":<>\d+$?]/g.test(str);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id=firstName />
Note: I don't care here to use e.which or e.keyCode because no need to in this case .. Also this regex will disable _ and . and - if you need any of those you can remove it
I am trying to add a keylistener to my input field but I can't make it work. My input type is text with id= "code". Here is what I tried:
document.querySelector('code').addEventListener('keypress', function (e) {
var key = e.which || e.keyCode;
window.alert(key);
});
and
document.getElementById('code').addEventListener("keydown", dealWithKeyboard, false);
function dealWithKeyboard(e) {
if (window.event) { // IE
keynum = e.keyCode;
} else if (e.which) { // Netscape/Firefox/Opera
keynum = e.which;
}
window.alert(keynum);
}
and
document.getElementById('code').onkeyup = function(e) {
if (window.event) { // IE
keynum = e.keyCode;
} else if (e.which) { // Netscape/Firefox/Opera
keynum = e.which;
}
window.alert(keynum);
}
But none seems to work
You aren't using the proper selector with document.querySelector(). An id value must be preceded by # as in document.querySelector('#code').
document.querySelector('#code').addEventListener('keypress', function (e) {
var key = e.which || e.keyCode;
console.log(key);
});
Working snippet:
document.querySelector('#code').addEventListener('keypress', function (e) {
var key = e.which || e.keyCode;
log(key);
});
// show output
function log(x) {
var div = document.createElement("div");
div.innerHTML = x;
document.body.appendChild(div);
}
Type some characters in the Input field here:
<input id="code">
Implemented properly, your document.getElementById('code') example should work.
If this still doesn't work, then check for two more things:
Make sure that you are executing this script AFTER the relevant parts of the DOM have been loaded. There are several ways to assure this, but the simplest is to just located the <script> tag after the HTML that it refers to.
Make sure that there are no script errors that are preventing your code from executing. You can check the debug console to check for errors.
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.
I have this code
function verifyKey(e)
{
var keycode;
if (window.event)
keycode = window.event.keyCode;
else if (e)
keycode = e.which;
regex=/[1-9]/;
if(regex.test(keycode))
return true;
else
void(0);
}
in the html I added an input and I add the onkeydown event onkeydown="verifyKey(event);"
I like to verify the key before it display on the text
If the key is a number or coma(,) or full stop(.)
then accept the key
else
refuse it
Thanks
Here in your code you are testing the regular expression defined with the keycode, so every chearactes on the keyboard will be allowed since the keycode of every key is numbers, so you will not get the result what you expect. Instead of using the regular expression try the below code
<html>
<head>
<script type="text/javascript">
function verifyKey(e)
{
var keycode;
if (window.event)
keycode = window.event.keyCode;
else if (e)
keycode = e.which;
if((keycode>=48 && keycode<=57))
{alert("if")
return true;
}
else if((keycode == 188)||(keycode == 190))
{alert("elseif");
return true;
}
else
{alert("else")
return false;
}
}
</script>
</head>
<body>
<input type="text" onkeypress="return verifyKey(event)" />
</body>
</html>
I have an input (outside form) that captures name of an image. User should fill in a new name and hit enter. Ajax callback renames the image. This works.
I'd like to add ability to 'reset' the input content when the user presses escape (#27). But I'm not able to fill the value of the input with my value.
The code is
<input id="escapeInput" value="this is test" /> <input type="button" id="setDetaultToEscapeInput" value="Set default" />
jQuery(document).ready(function() {
jQuery("#escapeInput").keydown(function(evt) {
if (evt.keyCode == 27) {
var input = jQuery(this);
input.val('some default value') // doesn't work
input[0].value = 'some default value 2'; // doesn't work
input.parent().append('changed');
}
});
jQuery("#setDetaultToEscapeInput").click(function() {
var input = jQuery("#escapeInput");
input.val('some default value') // works ok
});
});
The interesting thing is that if I test e.g. for 'A' character ( if (evt.keyCode == 65)), the code works.
Any idea how to handle it? It doesn't work only in FF (Opera and IE8 are OK).
Try using the keyup event instead.
$(function() {
$("#escapeInput").keyup(function(e) {
if (e.keyCode == 27) {
$(this).val("some default value");
}
});
});
Try this
$(document).ready(function () {
$("#escapeInput").keypress(function (evt) {
var keycode = null;
if (evt.keyCode) {
keycode = evt.keyCode;
} else {
keycode = evt.which;
}
if (keycode == 27) {
$(this).val("some default value");
}
});
});