I am trying to disable spaces in the Username text field, however my code disables using the back arrow too. Any way to allow the back arrow also?
$(function() {
var txt = $("input#UserName");
var func = function() {
txt.val(txt.val().replace(/\s/g, ''));
}
txt.keyup(func).blur(func);
});
fiddle: http://jsfiddle.net/EJFbt/
You may add keydown handler and prevent default action for space key (i.e. 32):
$("input#UserName").on({
keydown: function(e) {
if (e.which === 32)
return false;
},
change: function() {
this.value = this.value.replace(/\s/g, "");
}
});
DEMO: http://jsfiddle.net/EJFbt/1/
This seems to work for me:
<input type="text" onkeypress="return event.charCode != 32">
It doesn't "disable" the back arrow — your code keeps replacing all the text outright, whenever you press a key, and every time that happens the caret position is lost.
Simply don't do that.
Use a better mechanism for banning spaces, such as returning false from an onkeydown handler when the key pressed is space:
$(function() {
$("input#Username").on("keydown", function (e) {
return e.which !== 32;
});
});
This way, your textbox is prohibited from receiving the spaces in the first place and you don't need to replace any text. The caret will thus remain unaffected.
Update
#VisioN's adapted code will also add this space-banning support to copy-paste operations, whilst still avoiding text-replacement-on-keyup handlers that affect your textbox value whilst your caret is still active within it.
So here's the final code:
$(function() {
// "Ban" spaces in username field
$("input#Username").on({
// When a new character was typed in
keydown: function(e) {
// 32 - ASCII for Space;
// `return false` cancels the keypress
if (e.which === 32)
return false;
},
// When spaces managed to "sneak in" via copy/paste
change: function() {
// Regex-remove all spaces in the final value
this.value = this.value.replace(/\s/g, "");
}
// Notice: value replacement only in events
// that already involve the textbox losing
// losing focus, else caret position gets
// mangled.
});
});
Try checking for the proper key code in your function:
$(function(){
var txt = $("input#UserName");
var func = function(e) {
if(e.keyCode === 32){
txt.val(txt.val().replace(/\s/g, ''));
}
}
txt.keyup(func).blur(func);
});
That way only the keyCode of 32 (a space) calls the replace function. This will allow the other keypress events to get through. Depending on comparability in IE, you may need to check whether e exists, use e.which, or perhaps use the global window.event object. There are many question on here that cover such topics though.
If you're unsure about a certain keyCode try this helpful site.
One liner:
onkeypress="return event.which != 32"
Related
So I was trying replace the key press "K" with "Z" in an input field.
I was successfully able to do it. But there is a slight delay which makes the user see that the "K" being changed to "Z".
This is my code:
function prinner (event)
{
document.getElementById("txx").innerHTML= event.key; //Displays key pressed on screen by changing text element.
if(event.keyCode == 32){
// User has pressed space
document.getElementById("txx").innerHTML= "Space";
}
if (event.key=="k") // Trying to replace this with z.
{
var curval = $("#namaye").val(); //namaye is the ID of the input field.
var nval = curval.slice(0,(curval.length-1))+"z";
$("#namaye").val(nval);
}
}
$("#namaye").keyup(prinner);
Does anyone know a better way to achieve this without the delay?
Use keydown instead of keyup and cancel the event so the key stroke doesn't actually get printed:
function prinner (event) {
// Displays key pressed on screen by changing text element.
document.getElementById("txx").innerHTML= event.key;
if(event.keyCode == 32){
// User has pressed space
document.getElementById("txx").innerHTML= "Space";
}
// Trying to replace this with z.
if (event.key=="k") {
var curval = $("#namaye").val(); //namaye is the ID of the input field.
var nval = curval +"z";
$("#namaye").val(nval);
// Cancel the event
event.preventDefault();
event.stopPropagation();
}
}
$("#namaye").keydown(prinner);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="namaye">
<p id="txx"></p>
Use keydown event, and cancel the default behaviour when k is pressed. Also, use selectionStart and selectionEnd properties to replace the characters that were selected at the moment the key was pressed, and to put the cursor at the right position, just after the inserted z:
function prinner (event) {
$("#txx").text(event.keyCode == 32 ? "Space" : event.key);
if (event.key=="k") {
var s = $(this).val();
var i = this.selectionStart;
s = s.substr(0, i) + "z" + s.substr(this.selectionEnd);
$(this).val(s);
this.selectionStart = this.selectionEnd = i + 1;
return false;
}
}
$("#namaye").keydown(prinner);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="namaye">
<div id="txx"></div>
Since you use jQuery, use $("#....") instead of the more verbose document.getElementById("...."). Also, in the event handler, this will be input element, so use that reference.
Try using keydown? It happens before the input is actually modified: in fact, if you return false (or e.preventDefault()) inside a keydown listener, it will actually cancel the keystroke, which I think is what you want. Then you manually add your new key. Something like (untested and skipping some details for clarity):
function prinner (event)
{
if (event.key=="k")
{
event.preventDefault() // makes sure the 'k' key never goes to the input
$("#namaye").val( $("#namaye").val() + 'z' );
}
}
$("#namaye").keyup(prinner);
You have to add an event.preventDefault() inside your if clause to stop the event propagation and then you can insert your "z" key.
I have a scenario where i prevent user from entering 2nd numeric after a decimal.I have my code on keydown event.
Below is my code:
$scope.Inputkeydown = function (event, value) {
if (event.keyCode != 8) {
if (value != null && value != undefined && value != "") {
var regex = /^\d*\.\d$/; //this regex passes only decimal numbers with one digit after decimal
if (regex.test(value)) {
event.preventDefault();
}
}
}
};
Now the trouble is if user selects on the text(say 50.0) in the textbox and say presses 5 at that time it is getting prevented too, as in the textbox value is 50.0 and regex allows it go and it is getting prevented from being typed in.
Can i check on keydown if text is being copied?? or is there any other way around?
Instead of preventing the user from entering it, you could just remove it after keypress:
function filterDecimals(inp) {
return inp.replace(/^(\d*\.\d)\d*$/g, '$1');
}
Or, if you want to remove everything after it, replace the second \d* with .*
EDIT (example of usage)
This function takes the text as input and returns the new filtered text. To use this, just attach an event handler on keypress like so:
<input type="text" id="filteredbox">
<script>
var txt = document.getElementById("filteredbox");
// on keyup event (you can change to keypress if you want, but this is more logical here
txt.addEventListener("keyup", function(){
// sets value of txt to the returned data from filterDecimals()
// if statement: only filters it if necessary; this eliminates the "selected text" issue you mentioned
if (this.value !== filterDecimals(this.value)) {
this.value = filterDecimals(this.value);
}
});
</script>
I'd like to start an action (enabling autocomplete) when user types '#'. I have jQuery available.
Usually on a QWERTY keyboard, it is like this:
$('textarea').live('keydown', function(e) {
if (e.which === 50) {
console.log('# has been entered.');
}
});
However it does not work correctly on an AZERTY keyboard. The keyCode = 50 corresponds to the é~/2 key. To type '#' in AZERTY keyboard, it is AltGr + à#/0 key.
Edit: Autocomplete starts when # is entered, and only after that. Example, when someone enters "Hello #" then it starts, however when he types "Hello #nothing else" the complete won't do anything. Example: http://mrkipling.github.com/jQuery-at-username/ (it works only on QWERTY keyboard).
Use keypress instead of keydown. While keydown relates to every press of a key, keypress relates to the translated characters, so for example a can be different to a while the shift key is pressed, composed characters work, dead-keys work, and other differences in keyboard mappings are handled.
How about checking if # was entered as the last character in the field value?
$("body").on("keyup", "textarea", function(e) {
if (this.value.indexOf("#") == this.value.length - 1) {
console.log("Starting autocomplete");
}
});
DEMO: http://jsfiddle.net/FKhPW/2/
Use event.key and modern JS, checking for # directly!
No number codes anymore. You can check key directly.
const input = document.getElementById("textarea");
input.addEventListener("keydown", function (event) {
if (event.key === "#") {
// Do something
}
});
Mozilla Docs
Supported Browsers
The only other option that comes to mind would be a timer that checks the content of the text input.
var patt=new RegExp(/^#/);
var charCheck = setInterval(function(){
if (patt.test($("#textInput").val())){
// initiate autocomplete
}
},100);
This code will inspect the contents of the #textInput element and see if it matches the regular expression of a # symbol at the beginning of the string. If it does, the test() function will evaluate to true and you can initiate your autocomplete code.
Here you go working demo: http://jsfiddle.net/LxpQQ/
From my old reply here:
jquery autocomplete using '#'
Hope it will fit you cause :)
code
source: function(request, response) {
if (request.term.indexOf("#") >= 0) {
$("#loading").show();
getTags(extractLast(request.term), function(data) {
response($.map(data.tags, function(el) {
return {
value: el.name,
count: el.count
}
}));
$("#loading").hide();
});
}
},
I thought it would be a simple thing to hijack the space key when in a form input so that it would function like a hyphen. Generally jQuery makes stuff like this really simple.
The code I tried is this:
$("#StreamUrl").keydown(function (e) {
if (e.keyCode == 32) return 109;
});
But this has no effect whatsoever. I tried a more simple script:
$("#StreamUrl").keydown(function (e) {
//if (e.keyCode == 32) return 109;
alert(e.keyCode);
});
This script correctly alerts 32 on space press and 109 on hyphen press. Also, I have no JavaScript errors.
Why wouldn't if (e.keyCode == 32) return 109; work? When I replace that line with if (e.keyCode == 32) alert("space!!"); I get the alert correctly, so I know the if is returning true correctly.
What gives?
Edit - Solution
Thanks to #Nick for pointing out the copy-paste issue. I ended up with a little bit of a hybrid. Here's the code that I have gotten to work which is both smooth and handles Copy/Paste.
$("#StreamUrl").keydown(function (e) {
if (e.keyCode == 32) {
$(this).val($(this).val() + "-"); // append '-' to input
return false; // return false to prevent space from being added
}
}).change(function (e) {
$(this).val(function (i, v) { return v.replace(/ /g, "-"); });
});
The problem is that return 109 doesn't do what you want it to do. In an event handler, you return true or false depending on whether or not you want the browser to execute the default action. In keydown, you would return false to prevent the character from being inserted.
$("#StreamUrl").keydown(function (e) {
if (e.keyCode == 32) {
$(this).val($(this).val() + "-"); // append '-' to input
return false; // return false to prevent space from being added
}
});
jsfiddle example
You usually want the keyup event instead here, which fires after the space has been added, something like this is a bit easier:
$("#StreamUrl").bind("keyup change", function () {
$(this).val(function(i, v) { return v.replace(/ /g,"-"); });
});
Try it out here, what this does is allow the space to be added, but then instantly does a replace of spaces for hyphens by passing a function to .val(). For older versions of jQuery, it'd look like this:
$("#StreamUrl").bind("keyup change", function () {
$(this).val($(this).val().replace(/ /g,"-"));
});
This works even for people pasting content, an easy way to get around keydown validation.
I just started adding JS-validation to a signup form and I want the username input field in a Twitter-style (using jQuery). That means that the input is limited to certain characters and other characters do not even appear.
So far, I've got this:
jQuery(document).ready(function() {
jQuery('input#user_login').keyup(function() {
jQuery(this).val( jQuery(this).val().replace(/[^a-z0-9\_]+/i, '') );
});
});
This solution works, but the problem is that the illegal character appears as long as the user hasn't released the key (please excuse my terrible English!) and the keyup event isn't triggered. The character flickers in the input field for a second and then disappears.
The ideal solution would be the way Twitter does it: The character doesn't even show up once.
How can I do that? I guess I'll have to intercept the input in some way.
If you want to limit the characters the user may type rather than the particular keys that will be handled, you have to use keypress, as that's the only event that reports character information rather than key codes. Here is a solution that limits characters to just A-Z letters in all mainstream browsers (without using jQuery):
<input type="text" id="alpha">
<script type="text/javascript">
function alphaFilterKeypress(evt) {
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
var charStr = String.fromCharCode(charCode);
return /[a-z]/i.test(charStr);
}
window.onload = function() {
var input = document.getElementById("alpha");
input.onkeypress = alphaFilterKeypress;
};
</script>
Try using keydown instead of keyup
jQuery('input#user_login').keydown(function() {
Aside: You selector is slower than it needs to be. ID is unique, and fastest, so
jQuery('#user_login').keydown(function() {
Should suffice
You might want to consider capturing the keycode iself, before assigning it to the val
if (event.keyCode == ...)
Also, are you considering the alt, ctls, and shift keys?
if (event.shiftKey) {
if (event.ctrlKey) {
if (event.altKey) {
Thanks #TimDown that solved the issue! I modified your code a little so it accepts backspace and arrows for editing (I post a reply to use code formatting).
Thank you very much.
function alphaFilterKeypress(evt) {
evt = evt || window.event;
// START CHANGE: Allow backspace and arrows
if(/^(8|37|39)$/i.test(evt.keyCode)) { return; }
// END CHANGE
var charCode = evt.keyCode || evt.which;
var charStr = String.fromCharCode(charCode);
// I also changed the regex a little to accept alphanumeric characters + '_'
return /[a-z0-9_]/i.test(charStr);
}
window.onload = function() {
var input = document.getElementById("user_login");
input.onkeypress = alphaFilterKeypress;
};
You can use the maxlength property in inputs and passwords: info (that's actually the way Twitter does it).