we have an input type="text" user prints into it some string. each time he inputs empty space char we want to call some function. How to do such thing with jQuery?
$(input).keydown(function (e) {
if ( e.which === 32 ) {
// do your thing
}
});
where input is a reference to your INPUT element.
Live demo: http://jsfiddle.net/uHpLg/
Check out jQuery's keypress event:
$("#YourInputId").keypress(function() {
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 32) { // 32 = space keycode
//Do something
}
});
Here's a web page that has a list of javascript key codes.
Bind a listener to the input onchange event.
Compare the current value to the last value and check is the new character is a space
If so, call a function.
you can select the input text box and bind to it a change listener
but this will work only when the box is unfocused and the new value is different than the old value
$(document).ready(function () {
$('#mytextbox').change(function(){
if ($(this).val() == ' ')
{
// do whatever u want
}
});
});
but if u wanted something like autosuggestion (don't wait for user to unfocus the text input ) u can create ur own listener
is when the user focus the text box ,key press u check the pressed key and if it's is = " " do whatever u want
and when the user unfocus the input , it stops checking it
$('#mytextbox').keypress(function (e){
if (e.keycode == 32 )
{
// do your code here
}
});
for more info about keycodes : http://asquare.net/javascript/tests/KeyCode.html
on keypress Jquery function documentation : http://api.jquery.com/keypress/
Related
I am trying to stop cursor from deleting the word before it if the word before is "Hi Harry" in input type text . I am trying to restrict cursor from deleting text, if user started deleting text and
text before it matches "Hi Harry" before it then stop deleting this text. The user also should not override the "Hi Harry text" by selecting and typing another character. "Hi Harry" must not be deleted or replaced by user by any action.
Any solution that fulfills the requirement may help.
.html
<input id="target" type="text" value="Hi Harry">
js
$( "#target").keydown(function(e) {
if (e.which == 8 && e.target.value === "Hi Harry") {
// backspace or delete key
return false;
// here I want to stop cursor from deleting if user started deleting text and
//text before it if matches "Hi Harry" then stop deleting this text.
}
});
As you may know by now, to prevent the user from deleting with backspace or delete, you can preventDefault on the events for e.which == 8 or e.which == 46.
What if the user selects the text or clicks in between "Hi Harry?" You need to also handle some text selection events. See the snippet below[1]:
// monitor key down function
var initialValue = $("#target").val();
$("#target").keydown(function(e) {
if (e.target.selectionStart < initialValue.length) {
//prevent user from typing stuff in between "Hi Harry"
e.preventDefault();
return;
}
if ((e.which == 8 || e.which == 46) && e.target.value === initialValue) {
// backspace or delete key
// backspace is 8, delete is
e.preventDefault();
}
});
// monitor text selection and force to deselect
function handleSelections(e) {
e.preventDefault();
var endPoint = initialValue.length;
if (e.target.selectionEnd > initialValue.length + 1) {
endPoint = e.target.selectionEnd;
}
if (e.target.selectionStart < initialValue.length) {
e.target.setSelectionRange(initialValue.length, endPoint);
};
}
// prevent any selection of text until after "Hi Harry"
$("#target").get(0).addEventListener('select', handleSelections);
// prevent cursor positioning anywhere within "Hi Harry"
$("#target").get(0).addEventListener('click', handleSelections);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="target" type="text" value="Hi Harry">
[1] Tested on Google Chrome 78
You could just call the preventDefault method of the event argument that is passed to the callback function when these conditions are met :
BACKSPACE (e.which === 8) is being pressed.
the input's value is currently equals to Hi Harry.
a better approach is to store the initial value of input thus you'll be able to write anything as its initial value.
const inp = $("#target"), /** referening the input **/
initVal = inp.val(); /** store its initial value **/
/** keydown event handler **/
inp.on('keydown', e => {
e.which == 8 && inp.val() == initVal && e.preventDefault();
/**
* backspace and current value is the same as the initial value then just don't allow the backpace functionnality at this moment.
* if the conditions aren't met, simply the line won't work thus allow inputing.
**/
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="target" type="text" value="Hi Harry">
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 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"
I have an input box that always has focus. The commands that go into this input box are always letters. If the user presses a number, I would like it not to be added to the text box, but instead use it to run a different command (just like a hotkey).
The way I've seen this implemented is by looking at the keyup event and removing unwanted characters. Instead, is there any way to to intercept the keyboard input and check what the value is before the insert?
I've thought about creating a custom input field using a div and intercepting all the keyboard commands. Is there a way to get a blinking caret so that it looks like an input box?
Sounds like you want a contenteditable div:
<div id="editor" contenteditable="true"></div>
You can listen for keydown events and prevent them if they aren't letters:
$("#editor").keydown(function (e) {
if (e.which > 90 || (e.which > 48 && e.which < 65)) {
e.preventDefault();
}
});
To process the numbers as "hotkeys" you would just determine which key e.which is and act accordingly.
Example: http://jsfiddle.net/g3mgR/1
Something like this will work:
<input type="text" id="txt" />
For jQuery:
$('#txt').keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
if (key > 46 && key < 58) {
event.preventDefault();
alert('its a number, do something');
}
});
Here is the Fiddle
Use keydown instead of keyup.
Use the keypress event in combination with String.fromCharCode:
document.getElementById('yourTextBoxID').onkeypress = function () {
var characterPressed = String.fromCharCode(event.keyCode);
if (characterPressed.test(/[a-z]/i)) {
// user pressed a letter
} else {
// user did not press a letter
}
};
http://jsfiddle.net/TSB9r/3/