Unfocusing textbox with jQuery when key pressed - javascript

I have a textbox that displays an alert when you click outside the textbox. I'm trying to also display the alert if the user presses Enter. Here's what I have:
<input id="txtInput" type="text" onblur="alert('Hello');" />
<script type="text/javascript">
$(document).ready(function () {
$("#txtInput").keyup(function (event) {
if (event.keyCode == 13) {
$(this).blur();
return false;
}
});
});
If I click inside the textbox and then click outside it, the alert shows correctly.
But if I'm inside the textbox and push Enter, it shows the alert - when I dismiss the alert, another alert shows (I assume because onblur is being called on the textbox).
Why doesn't calling $(this).blur() remove the focus from the textbox? Or is there a better way to do this?

Why this works, I can't tell you, but if you remove the onblur event from your HTML and put it into your js, it works.
http://jsfiddle.net/ERdaa/4/
$("#txtInput").keyup(function (event) {
if (event.keyCode == 13) {
$(this).blur();
return false;
}
}).blur(function(){
alert('Hello');
});
[edit] cleaned up code to use chaining instead of using selector twice.

Related

toggling the focus from button to Text box using enter key to which an event is binding

$('#b').on('click', function() {
$('#in2').focus();
//setTimeout(function(){ $('#in2').focus(); },500);
});
$('#in2').on('keyup', function(event) {
console.log(event.which);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="b">focus</button>
<input type="text" id="in1" />
<input type="text" id="in2" />
I have a key up function bound to button where I am shifting my focus to text field #in2 in the above example.
And I also have a key down event bound for text field #in2.
Problem: When I am using the enter key on the button, event bound to the text field(#in2) is getting called.
Can someone suggest me some solution except setTimeout?
If I understand your problem correctly and you don't want the function on keyup on #in2 called when Enter is pressed, just check whether the pressed key is enter and only execute it if it isn't?
$('#in2').on('keyup', function(event) {
if(event.which != 13){
console.log(event.which);
}
});
Alternatively you could use onchange so that the function gets called when the content of the element changes (this would also work with copy-and-past for example)

jQuery - Replacing HTML element multiple times

I want to replace a button with an input field, where the user enters something and presses the enter button. After that, the button from the beginning should appear again. My script works so far but I can't repeat this once it finished.
Update: The button should also appear again, if the input field is shown but the user don't want to enter anything and clicks somewhere else.
The code:
<button id="createButton">Create item</button>
/*
jquery stuff
*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#createButton').click(function( event ) {
$(this).replaceWith('<input type="text" id="buttonInput" placeholder="e.g. books, movies" autofocus>');
});
$(this).on('keypress', function (event) {
if(event.which == '13'){ // If enter button is pressed
alert('You entered something');
$('#buttonInput').replaceWith('<button id="createButton">Create item</button>');
}
});
});
</script>
Update 2: I updated the code with hide() and show() to get the same result. But how can I let the input disappear, if the user clicks somewhere inside the body, without redundancy?
The new code:
<button id="createButton">Create item</button>
<input type="text" id="input" placeholder="e.g. books, movies" autofocus>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#input').hide();
$(document).on('click', '#createButton', function (event) {
$(this).hide();
$('#input').show().focus();
});
$('#input').on('keypress', function (event) {
if (event.which == '13') { // if enter button is pressed
$(this).hide().val('');
$('#createButton').show();
}
});
});
</script>
As the other answers say, you're replacing the element (createButton), which means the click handler is no longer bound.
You can either re-bind, or bind to the parent element, with the #createButton selector using on.
$(document).on('click','#createButton', function( event ) {
...
});
Don't actually use document - use whatever the parent element is, which doesn't get replace (a div, perhaps?)
Replacing DOM elements is a bad approach though -- you'd be better off leaving the elements on the page, and using show and hide.
http://jsfiddle.net/v03j8bns/
Updated Answer
Here's a fiddle showing the show/hide/ approach. To handle:
The button should also appear again, if the input field is shown but the user don't want to enter anything and clicks somewhere else.
When the button is clicked, I call focus() on the textbox. I've also hooked up a blur() event handler, so if the user clicks/tabs out, then it'll hide the textbox and show the button.
You have to bind the click event to newly created button again:
$(document).ready(function () {
$('#createButton').click(function (event) {
$(this).replaceWith('<input type="text" id="buttonInput" placeholder="e.g. books, movies" autofocus>');
});
$(this).on('keypress', function (event) {
if (event.which == '13') { // If enter button pressed
//Disable textbox to prevent multiple submit
alert('You entered something');
$('#buttonInput').replaceWith('<button id="createButton">Create item</button>');
}
$('#createButton').bind('click', function (event) {
$(this).replaceWith('<input type="text" id="buttonInput" placeholder="e.g. books, movies" autofocus>');
});
});
});
You have this issue because you replace DOM elements. It means that your new element button no longer has click handler.
I would recommend you to use something like show/hide or use jQuery delegate on/bind for handling click.
When you're changing DOM on the fly and want to automatically assign listeners to elements that may or may not exist at certain points of time, you need to use delegated event listeners.
$(document).on('click', '#createButton', function () { ... });
$(document).on('click', '#buttonInput', function () { ... });
These handlers will work however you scramble the DOM.

Jquery: Enter to blur

Please check out this fiddle: http://jsfiddle.net/7wp9rs2s/ this is how far I have come with this project.
Basically, in the above fiddle you can double click on one of the 4 items and when you do, you get a textbox where you can edit it. Then you click out and it goes back to being a text. Most users wont click out but will instead press enter (like SO's comment function) so if the user presses enter, while making the edit, I want the script to react in the same way as if the user clicked out of the box.
I know how to capture the Enter key:
$(document).keypress(function(e) {
if(e.which == 13) {
alert("in Enter");
}
});
But I do not know how to make the function do what I need :(
Your functions are called on blur, so simply trigger a blur on the input :
$(document).keypress(function(e) {
if(e.which == 13) {
$(e.target).blur();
}
});
Fiddle

Prevent Enter key works as mouse click

I noticed that if you focus on an element that mouse clic can be triggered, the Enter keys acts like as you left click the mouse. I want to avoid this running since it comes into conflict in other pieces of my code.
In the following example if I focus on this imageButton and I clic once, the next clicks can be "done" with the Enter key, so I don't want this because this button fires a slideToggle() and shows a hidden div, so IMO it's pointless toggle this div with the keyboard.
Is there any way to make it global way?
Thank you.
Try this:
$(".myElements").keypress(function(e) {
if (e.which == 13) {
e.preventDefault();
}
});
It will stop the enter key behaviour only, allowing the other key functions to work as usual.
Listen for "keypress" and .preventDefault()
ex. with <myelm class="nokey"/>
function noKeyPressing(){
var elms = document.getElementsByClassName('nokey'),
stop = function stop(e){ return e.preventDefault(), false; },
i = elms.length;
while(--i >= 0){
elms[i].addEventListener('keypress', stop, true);
}
}
noKeyPressing()
If you just want to prevent Enter then the keyCode to look for is 13.
try
.unbind('keydown');
to disable all key events on your element
You can return false to prevent the default action.
<input type="submit" onkeypress="return false;" value="Submit" />
An other possible way i think:
$('.elems').on('click',function(){$(this).blur()});
try this code
$('body *').keypress(function (e) {
if (e.which == 13) {
e.preventDefault();
}
});
the above code will prevent pressing enter for every element in page
,You can change the selector $('body *') to something else depending to your case

JQuery Event for when user presses enter?

What's the simplest way to have a function called whenever the user hits enter after typing in a textbox?
You'll need to listen for the keypress event. It's probably easiest to do this with delegate:
$(document.body).delegate('input:text', 'keypress', function(e) {
if (e.which === 13) { // if is enter
e.preventDefault(); // don't submit form
// do what you want here
}
});
<textarea id="text"></textarea>
$('#text').keydown(function(e){
if (e.keyCode == 13) {
alert('Enter was pressed.');
}
});
http://jsfiddle.net/dNfC2/
HTML code
<input type="text" id="txt"/>
<input type="button" id="btn" value="send"/>
jquery code
$("#txt").keydown(function(event){
if(event.keyCode == 13){
alert("enter button pressed");
$("#btn").click();
}
});
Running example here : http://jsfiddle.net/Xamkp/5/
try this:
jQuery(document).bind('keydown', 'return',function (){ /*do something*/ });
you will need a plugin:
jquery.hotkeys
Well it's rather simple to do in the form you asked:
$('#idOfTextBox').keyup(function(event){
// enter key pressed
if(event.keyCode=='13')yourFunction();
});
Take note this will still append the enter key to the box. You might wanna try keydown or keypressed if you don't want that.
Be sure to check keyUp() for more detail.
Put the <input> in a form, and write a handler for the form's submit event.
This way you're not explicitly looking for any particular key; you're just waiting for the form to be submitted normally. And in every mainstream browser, pressing enter while filling out a form will submit the form.
Note that you do not need to have a physical submit button on the screen if you don't want (in which case the enter key will likely be the only way to submit the form).

Categories