Is there any way to replay a keyboard event to a textfield and also make the receiving input field add that character to its text? Because I can't make it to work.
Let's say I press a on the keyboard and a global handler on body captures it. Now I want to replay it to a given textfield. So if the user presses a on the keyboard it would show up inside the textfield, solely based on the event. The event pops up at the input, but the character is not inputted. Is this possible? I want to avoid manipulating the input text with .val();
Example:
$('body').on('keyup', eKeyUp);
$('#mancineni').on('keyup', eKeyUpINPUT);
function eKeyUp(e)
{
$e = $.Event('keyup');
$e.which = e.which;
$e.charCode = e.charCode;
$e.keyCode = e.keyCode;
$e.shiftKey = e.shiftKey;
$e.key = e.key;
$('#mancineni').trigger($e);
//$('#mancineni').focus();
}
function eKeyUpINPUT(e)
{
console.log('g', e)
e.stopPropagation();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="mancineni">
It feels like you are making this much more difficult than it actually is. Just set the value of the input to event.key while handling it at the body level. Not sure why the need to avoid doing that, perhaps you could explain.
$('body').on('keyup', eKeyUp);
$('#mancineni').on('keyup', eKeyUpINPUT);
function eKeyUp(e){
$('#mancineni').val(event.key);
}
function eKeyUpINPUT(e){
e.stopPropagation();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="mancineni">
Related
I would like to trigger a click if enter is pressed inside an input tag, but would like to have the default event strategy in all other cases. I have tried it this way:
$("#keywords").keypress(function(e) {
if (e.charCode === 13) {
$("#campus-search").click();
} else {
$("#keywords").val($("#keywords").val() + String.fromCharCode(e.charCode));
}
});
It works, but I am still not satisfied, because when I click inside the input somewhere in the middle of text or press the left button, or home button and then try to type some text, it will show it at the end of the input, which is bad user-experience. Can I keep the input to work in the default way except the case when enter is pressed?
I think what you are looking for is this:
$(document).ready(function () {
$("#test").keyup(function (event) {
if (event.keyCode == 13) {
$("#campus-search").click();
}
});
$("#campus-search").click(function () {
console.log("BUTTON IS CLICKED");
});
});
The input will act completely normal and everything works on default, unless when you press the enter button (keyCode = 13), then the button .click() event will be triggered.
Working Fiddle: http://jsfiddle.net/Mz2g8/3/
————
# Update: Just one hint for the code in your question, do not use charCode, as it is deprecated.
This feature has been removed from the Web. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.
(E.g. charCode does not work with FF v29.0.1)
And something different but important to know:
charCode is never set in the keydown and keyup events. In these cases, keyCode is set instead.
Source: https://developer.mozilla.org/en-US/docs/Web/API/event.charCode
This should work
$("#keywords").keypress(function(e) {
if (e.charCode === 13) {
e.preventDefault(); // prevent default action of the event if the event is keypress of enter key
$("#campus-search").click();
} else {
$("#keywords").val($("#keywords").val() + String.fromCharCode(e.charCode));
}
});
I think you can eliminate the else clause entirely to get your desired result.
Look at this jsfiddle.
The keypress function does not capture non-printing keys, such as shift, esc, delete, and enter, so the best way to go about this would be have two event handlers: one for keypress, as you have defined above, and one for keydown that checks for the charCode 13 and then performs the click() event on $(#campus-search) if that keycode is passed (by an enter press).
Demo
This is what you are looking for:
HTML:
<input id="keywords" type="text" value="" />
<input id="campus-search" type="button" value="Campus Search" />
JavaScript / jQuery:
$("#keywords").keypress(function (e) {
if (e.charCode === 13) {
$("#campus-search").click();
} else {
$("#keywords").val($("#keywords").val() + String.fromCharCode(e.charCode));
}
});
$("#campus-search").on("click", function () {
alert("Searching..");
});
Live Demo
I'm new to JavaScript, and was wondering if there is a way to check where the focus was before the user pressed the Enter button. I want to process things differently based on the focus. Any ideas?
I guess that based on the focus means that if the user presses enter on an input you want to do one thing, and if the user presses enter into another input do something else.
if I am right, you don't have to check where the focus was. You want to bind functions to the onkeypress event.
<script>
function doStuffOnEnter()
{
var x = event.keyCode;
if(x == 13) // if user pressed intro
{
//do stuff
}
}
</script>
<input type="text" onkeypress="doStuffOnEnter()" />
the above code its very basic, but it's only for you to get the idea.
more info here: http://www.w3schools.com/jsref/event_onkeypress.asp
If your site makes use of jQuery, which is common for those new to JavaScript, then you can store the DOMElement in a global variable for you to check.
var currentFocus = null;
$('input, textarea').focus(function() {
currentFocus = this;
});
This will allow you to know where the user last was "focused" when he pressed enter.
If you're not using jQuery, the code would be a little longer but the same idea.
I have an input element and I want to keep checking the length of the contents and whenever the length becomes equal to a particular size, I want to enable the submit button, but I am facing a problem with the onchange event of Javascript as the event fires only when the input element goes out of scope and not when the contents change.
<input type="text" id="name" onchange="checkLength(this.value)" />
----onchange does not fire on changing contents of name, but only fires when name goes out of focus.
Is there something I can do to make this event work on content change? or some other event I can use for this?
I found a workaround by using the onkeyup function, but that does not fire when we select some content from the auto completer of the browser.
I want something which can work when the content of the field change whether by keyboard or by mouse... any ideas?
(function () {
var oldVal;
$('#name').on('change textInput input', function () {
var val = this.value;
if (val !== oldVal) {
oldVal = val;
checkLength(val);
}
});
}());
This will catch change, keystrokes, paste, textInput, input (when available). And not fire more than necessary.
http://jsfiddle.net/katspaugh/xqeDj/
References:
textInput — a W3C DOM Level 3 event type. http://www.w3.org/TR/DOM-Level-3-Events/#events-textevents
A user agent must dispatch this event when one or more characters have
been entered. These characters may originate from a variety of
sources, e.g., characters resulting from a key being pressed or
released on a keyboard device, from the processing of an input method
editor, or resulting from a voice command. Where a “paste” operation
generates a simple sequence of characters, i.e., a text passage
without any structure or style information, this event type should be
generated as well.
input — an HTML5 event type.
Fired at controls when the user changes the value
Firefox, Chrome, IE9 and other modern browsers support it.
This event occurs immediately after modification, unlike the onchange event, which occurs when the element loses focus.
It took me 30 minutes to find it, but this is working in June 2019.
<input type="text" id="myInput" oninput="myFunction()">
and if you want to add an event listener programmatically in js
inputElement.addEventListener("input", event => {})
As an extention to katspaugh's answer, here's a way to do it for multiple elements using a css class.
$('.myclass').each(function(){
$(this).attr('oldval',$(this).val());
});
$('.myclass').on('change keypress paste focus textInput input',function(){
var val = $(this).val();
if(val != $(this).attr('oldval') ){
$(this).attr('oldval',val);
checkLength($(this).val());
}
});
Do it the jQuery way:
<input type="text" id="name" name="name"/>
$('#name').keyup(function() {
alert('Content length has changed to: '+$(this).val().length);
});
You can use onkeyup
<input id="name" onkeyup="checkLength(this.value)" />
You would have to use a combination of onkeyup and onclick (or onmouseup) if you want to catch every possibility.
<input id="name" onkeyup="checkLength(this.value)" onmouseup="checkLength(this.value)" />
Here is another solution I develop for the same problem. However I use many input boxes so I keep old value as an user-defined attribute of the elements itself: "data-value". Using jQuery it is so easy to manage.
$(document).delegate('.filterBox', 'keyup', { self: this }, function (e) {
var self = e.data.self;
if (e.keyCode == 13) {
e.preventDefault();
$(this).attr('data-value', $(this).val());
self.filterBy(this, true)
}
else if (e.keyCode == 27) {
$(this).val('');
$(this).attr('data-value', '');
self.filterBy(this, true)
}
else {
if ($(this).attr('data-value') != $(this).val()) {
$(this).attr('data-value', $(this).val());
self.filterBy(this);
}
}
});
here is, I used 5-6 input boxes have class 'filterBox',
I make filterBy method run only if data-value is different than its own value.
I have a HTML form on my page. When i am putting some value in one of the text fields in form and press 'Enter key' the form gets submitted instantly. I think this is happening due to default focus is on submit button. But i try to remove that focus using blur() function, it is not working. I am using Chrome.
Is there any way to avoid this scenario?
All suggestions are welcome. thanks in advance.
The Submit button is not actually focused; Enter in a text field is supposed to submit the form.
You could register a handler for the submit event, and then only allow it if the Submit button was actually focused at the time submit was requested.
However, you'll be deliberately breaking the way that HTML forms work. Not everyone wants to submit the form using the One True Way of actually clicking the Submit button (also, you'll be breaking accessibility and may introduce browser-specific bugs).
No. The focus is still on the text field. Pressing enter there is supposed to submit the form (and bypasses the submit button entirely).
You can suppress the behavior using JavaScript, but since it is normal behavior for the browser, I wouldn't recommend doing so.
try this solution: replace the 'input' with 'button' and add attribute
type equals 'button' and handle the onclick event with submit javascript function
<form name='testForm'>
<input type='text' value="myName" />
<button type='button' onclick='testForm.submit()'/>
</form>
i think it works also with tag input adding the same attribute
Enjoy
Mirco
blur() is the way to go. It works like this:
<button onclick="this.blur();">some button</button>
Note that you should not use JavaScript and DOM-events using Attributes. This is just for demonstration purposes. Try to be unobstrusive.
Maybe it will help you out, the form is "supposed" to be sent with enter in the text box (HTML by design), it is no a matter of focus.
If you want to avoid it, check this out.
This is the proposed script:
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
}
Good luck, tell me if you need any clarification!
EDIT: I do agree with Piskvor answer, it may bring some bugs
this has nothing to do with the focus, its just the default behavior of you browser. to avoid this, you could try to cath the enter-keypress like this (Source - but there are a lot of other solutions (most working the same way, just using other events like the firms onsubmit instead of the documents onkeypress)):
function catchEnter(e){
// Catch IE’s window.event if the
// ‘e’ variable is null.
// FireFox and others populate the
// e variable automagically.
if (!e) e = window.event;
// Catch the keyCode into a variable.
// IE = keyCode, DOM = which.
var code = (e.keyCode) ? e.keyCode : e.which;
// If code = 13 (enter) or 3 (return),
// cancel it out; else keep going and
// process the key.
if (code == 13 || code == 3)
return false;
else
return true;
}
// Anonymous method to push the onkeypress
// onto the document.
// You could finegrain this by
// document.formName.onkeypress or even on a control.
window.onload = function() { document.onkeypress = catchEnter; };
Change:
<input type="text" ... >
To:
<textarea ... ></textarea>
You may need to mess around with the attributes a bit, I've left them signified as ....
try to add on the keypress event of your button this javascript function :
function ButtonKeyPress()
{
var code = (window.event.which) ? window.event.which : window.event.keyCode;
if ( code == 13 )
{
event.returnValue = false;
return false;
}
return true;
}
So, you have a form. In this form, you have a text input, and a submit button.
You get in the text input, you type some text, than you press "Enter". This submits the form.
You would like to break this normal behavior.
I think this is not a good idea : The convention says that when your in a text input and press "Enter", it submits the form. If you change this behavior, users could be (I don't find the right word, let's say ~) surprised.
Anyway, if you still want to do this, you should listen for the keypress event on the text input, and than prevent default behaviour shoud do the work.
let's say you use jQuery :
$(input[type=text]).bind('keypress', function(evt) {
if(evt.keyCode == 13) {
evt.preventDefault();
}
});
This should do it. I didn't test it, maybe I made mistakes, but you got the idea, no ?
And maybe keyup is better than keypress... I don't know very well this, not enough practice on key bindings
The easiest way is to set css style like this:
&:focus {
outline: 0 none;
}
I first used the onKeyUp event to detect input changes in a textbox. However, when the user enters in a French character using ALT+Num, the event doesn't detect the change until i enter the next character...
Which event should I be using to detect the special character changes. I've tried onChange but does not seem to be working.
I've tried using onkeypress event because I notice that it triggers it after i release the ALT key, however even though once the ALT is release, the onkeypress is triggered and you see the accented character, but when I use this.value for the inputbox, it only registers up to and before the new ALT+Num character is input.
for example: i entered vidé, but the search would not dynamically find vidé, but only vid because the é has not been saved in the - this.value yet, until another key event is triggered.
Hence I was wondering if there's way to simulate/send a key press to trigger it.
FINALLY FIGURED IT OUT!! :D
here's the code, however the String converting event.which code does not work on the jsFiddle though, nonetheless the code works :)
$('#i').keydown(function() {
document.getElementById('j').value = "down";
$('#k').val($('#i').val())
});
$('#i').keyup(function() {
document.getElementById('j').value = "up";
$('#k').val($('#i').val())
});
$('#i').keypress(function(event) {
$('#k').val(String.fromCharCode(event.keycode));
});
$('#i').change(function() {
document.getElementById('j').value = "change";
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="i" type="text" /><br />
<input id="j" type="text" />
<input id="k" type="text" />
View on JSFiddle
use keyup. The new character will not be added until the user releases the ALT key and at that point the keyup event will fire.
There's a reference at http://unixpapa.com/js/key.html which might be a good idea to have a look at, and according to section 2.1, ALT should generate a keydown and keyup in modern browsers..
I would suggest you use jQuery or a similar library to ease the issues you're facing cross-browser. Have a look at http://jsfiddle.net/qvDbu/1/ for a proof of concept which works fine.
Keypress is not triggered by only modifier-presses, so that's probably the way to go, it allows you to pick up the character entered as well, rather then which key is pressed. Edit: Seems to not be the case in Fx that keypress is triggered by modifiers, but I'm not able to reproduce actually loosing any characters.
The character entered with the ALT+NUM combination will only be added to the input element's value after the keyup event triggers, so you won't be able to read it in that event handler.
In order to solve this problem you could set a timeout on the ALT keyup event before reading the input element's value:
$('input').on('keyup', function (e) {
var _this = this;
var ALT_KEY_CODE = 18;
if (e.which == ALT_KEY_CODE) {
setTimeout(function () {
handleKeyup.call(_this , e);
}, 1);
} else {
handleKeyup.call(_this , e);
}
});
function handleKeyup (e) {
// $(this).val() now holds the ALT+NUM char
}
You need to bind onkeypress, which won't fire until you finish entering the alt code.
document.getElementById('input').onkeypress = function() {
alert('fired');
}
<input id='input' type='text' />
View on JSFiddle