use Jquery to set focus to input with keydown - javascript

I am using a site that has a search box and I would like it so when you press the space bar but don't have the search text box selected, the search text box gets focus and has it's text cleared. I have it about done, but the check to see if the search box has focus isn't functioning properly. Any suggestions on my code? As is, if you press the space bar, it clears the search box, even if you're typing in the search box.
document.addEventListener('keydown', function (event) {
if (event.keyCode == 32) {
if ($('#searchTextBox').not(':focus')) {
$("#searchTextBox").focus().select();
}
}
});

While you delegate a keydown event on the document, you can also check if the source/target is the textbox itself by using event.target. If the event comes from the text field, just ignore it.
$(document).on('keydown', function (event) {
if (event.which == 32 && event.target.id != 'searchTextBox')
$("#searchTextBox").focus().select();
});
Working example : https://jsfiddle.net/DinoMyte/mdu5fxkq/3/

Maybe this will work
$(document).ready(function(){
$(document).on('keydown',function(event){
if(event.keyCode==32){
if(!$('#search').is(':focus')) {
$('#search').focus().select();
}
}
});
});
Grettings!

Even Simpler
Check for the keyCode as 32 is for spacebar and you can use any other by using its code
$(document).on('keydown', function (event) {
if (event.keyCode== 32) {
$("#searchTextBox").focus().select();
}
});

Related

Simulate keypress on contenteditable element with jQuery

How to simulate keypress inside of a contenteditable div Programatically?
I want to remove characters programatically with a jQuery script without any human typing.
I would like to delete some characters from the end of the span tag with simulating a Backspace keypress inside of the contenteditable div.
<div class="editor" contenteditable="true">
<span>This is a span!!</span>
</div>
So the result would be something like this:
This is a span
I wouldn't like to rewrite the text. I need to simulate backspace keypress. Tested with this code, but nothing happened.
$(document).ready(function(){ // after the website loaded
// I want to trigger a keypress (backspace key)
// inside of the contenteditable div Programatically
$('.editor').trigger(jQuery.Event('keypress', { keycode: 8 }));
});
Can you help me?
I used some part of code that was mentioned in the comments: SO answer - Yuri
Here is the part that triggers the keydown event
$(document).ready(function(){ // after the website loaded
// I want to trigger a keypress (backspace key)
// inside of the contenteditable div Programatically
var e = jQuery.Event("keydown");
e.which = 8; // backspace key
$(".editor").trigger(e);
});
After that, I created a handler to .editor element
$(".editor").keydown(function(e) {
if (e.originalEvent === undefined) {
console.log('triggered programmatically');
} else {
console.log('triggered by the user');
}
console.log("Key pressed:" + e.which);
if(e.which == 8) {
// do your stuff
}
});
I also, put a validator to check if the event was trigged by user or programmatically.

jQuery keypress to work normally except hitting enter

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

keyup event not triggered for escape key

I have a text input field referred to as $nameEditor. I want to show this text field when a button is pressed, and hide it on blur or when the escape key is pressed.
Hiding the field on blur works every time.
Hiding the field when pressing the escape key works only the first time. Example sequence of events.
Press the button that shows the text input field.
Press escape - text input field hides
Press the button that shows the text input field again.
Press escape - the keyup event is not triggered
Press any other key and the keyup event is triggered
Press escape - the text input field hides
Relevant markup:
<button id="renameButton" title="Rename" data-icon="ui-icon-pencil">Rename</button>
<span id="assemblyNameView">Assembly Name</span>
<input id="assemblyNameEditor" style="display:none" class="ui-corner-all widget">
Relevant script:
var $renameButton = $("#renameButton");
var $nameViewer = $('#assemblyNameView');
var $nameEditor = $('#assemblyNameEditor');
function cancelEdit() {
$nameEditor.hide();
$nameViewer.show();
}
function initEdit() {
$nameViewer.hide();
$nameEditor.val($nameViewer.text()).show().select();
}
function commitEdit(newName) {
// TODO: Update the structure being edited.
$nameEditor.hide();
$nameViewer.text(newName);
$nameViewer.show();
}
$renameButton.click(initEdit);
$nameEditor.blur(cancelEdit);
$nameEditor.keyup(function(e) {
console.log(e);
if (e.keyCode === 13) {
var newName = val();
if (newName === '') {
alert("No name specified.");
$nameEditor.val($nameViewer.text()).select();
e.preventDefault();
return false;
}
commitEdit(newName);
}
else if (e.keyCode === 27) {
cancelEdit();
}
});
Why is the escape key not triggering the keyup event after the input box has been hidden then re-shown?
It's hard to explain what's wrong here. There is a strange effect when both the button and the textbox receive focus? It's impossible in a standard UI interface. In fact when you type keys other than ESC, Enter, Space and maybe more ... the typed characters are shown OK in the textbox and only the textbox receives focus after that. However if you type ESC, Enter, Space... the keystrokes seem to affect on the button and I can even see there is some color effect on the button showing that it's currently focused. This looks like a bug indeed.
However to solve this, I tried using focus() explicitly appended after .select() and it works OK.
function initEdit() {
$nameViewer.hide();
$nameEditor.val($nameViewer.text()).show().select().focus();
}
Demo.

How to handle keypress of default button?

I thought I'd handle not clicking on my default button (which is on my asp.net master page) by checking if enter was pressed and handling it. Basically when users were on any input type fields and they hit enter, it would actually execute the event of my default button on my form (as mentioned it is a button on my master page that allows for a global search).
So users were like hey wait a minute i hit the enter key on an input field why am I suddenly on a search results page....I dont blame them...
I thought I'd handle it with this:
$(document).keypress(function (e) {
if (e.which == 13) {
return false;
}
});
Which the problem no longer happened, and I was happy...until I found out all my buttons on for instance my jquery dialog no longer executed when you tabbed to them and hit the enter key...Well I see the reason why because I'm returning false. But how should I structure this so this does not happen if you are focused in on a for example asp.net button?
You should only on handle textboxes
$('input[type=text]').keypress(function (e) {
if (e.which == 13) {
return false;
}
});
EDIT
As per comment, Can I add this in my site.master page but ignore one specific text box
Excluding a textfield
$('input[type=text]').not('.search').keypress(function (e) {
if (e.which == 13) {
return false;
}
});
Here I have include a demonstration, In last textbox (search) event is not associated.
Use Event Delegation Approach
$(document).on('keypress', 'input[type=text]:not(.search)', function (e) {
if (e.which == 13) {
alert('Enter pressed')
}
});
DEMO
You need to bind even to exact element on page:
$('.aspNetButton').on('keypress', (function (e) {
if (e.which == 13) {
return false;
}
});

.live listner to check if user pressed tab to focus on current input field

I have a few input fields one on top of each other, I want to be able to check if a user used the tab key or clicked to focus on the current input field.
Checking on the .live('click', function() { is easy but i don't know how to check if they used tab to focus on the current input field.
I’m sure there are many ways to do this, but one way is to listen for the keyup event and then find out what element is focused, if any:
$(document).on('keyup', function(e) {
if(e.keyCode == 9) {
var input = $(this).find('input:focus');
// input is the element that has focus after the tab key was pressed
}
});
This might not be a guarantee that the tab key was used to bring focus to the element, but it might be sufficient for what you need.
If you want to check the event type that the user used before an input field gained focus, try:
$(document).on('keyup', function(e) {
if(e.keyCode == 9) {
findFocus(e);
}
}).on('click', 'input', findFocus);
function findFocus(e) {
var input = $(document).find('input:focus');
if ( input.length ) {
alert('Input was focused using '+e.type);
}
}
Also note that I used the .on() event instead of .live(), since live is deprecated in 1.7.
Sounds like you want the "focus" event which will fire if the user clicks on OR tabs to the field
.on('focus', function() {});
also this answer notes that "live" is deprecated, use "on" instead
https://stackoverflow.com/a/4944344/703173
$('input').on('click', function() {
$(this).data('clicked', true);
}).on('focus', function() {
setTimeout(function(){
if($(this).data('clicked') == true){
// clicked to focus
}else{
// used tab key to focus
}
$(this).data('clicked', false);
}, 100);
});

Categories

Resources