This question has been asked/answered (mostly) before, BUT I've tried three things to stop the event from bubbling but nothing has worked:
return false;
e.stopPropagation();
e.preventDefault();
(return false should take care of the other two, correct?)
Here's the html:
<div class="tags-holder">
<input type="text" class="addField" id="addField_<%= visit.id %>" placeholder="add a new tag">
</div>
And the JS (UPDATE CLEANED UP):
$('.addField').show().keyup(function(event){
event.preventDefault();
if(event.keyCode == 13 || event.keyCode==9) {
ProfilePage.createTag( this, 'nada', 'addField')
$(this).hide().val('');
return false;
}
});
I left the redundant stoppers in there but really shouldn't return false simply kill the bubbling? (using Chrome).
Clue? keyCode=13 is "Enter"
Wow. Your help was great and helped me think it through.
BUT the solution feels a bit like a cop-out; effective, but the condition should never be there in the first place.
Here it is, which I found in the comments from here:
http://yuji.wordpress.com/2010/02/22/jquery-click-event-fires-twice/
$('.plus').unbind('click').bind('click',function(e){
console.log('clicked')
var id=$(this).attr('plus_id');
var field=$('<input type="text">').attr({'placeholder':'add a new tag','id': 'addField_' + id, 'visit_id':id});
field.focus();
field.show().keydown(function(event){
event.stopImmediatePropagation();
if(event.keyCode == 13 || event.keyCode==9) {
console.log(event)
ProfilePage.createTag( field, 'nada', 'addField')
field.hide().val('');
return false;
}
}).click(function(e){
return false;
})
;
$(this).append(field);
return false;
});
I had same issue and I used above method and it work for me.
$(document).unbind('keypress').bind('keypress', function (e) {
// some logic here
});
Try unbinding the event first then bind it, refer below code:
$('.addField').show().unbind('keyup').keyup(function(event){
event.preventDefault();
if(event.keyCode == 13 || event.keyCode==9) {
ProfilePage.createTag( this, 'nada', 'addField')
$(this).hide().val('');
return false;
}
An explanation is here, i had written a post about this on my new blog.
Hope this will solve your problem.
Instead of using event.preventDefault() use these two shown below.
In case of Microsoft browsers use
event.cancelBubble = true;
In case of W3C model browsers use
event.stopPropagation();
And Instead of Keyup event kindly use the keypress event, because during keypress itself the input will be sent to input field so whatever inputs you don't want to appear will appear on the field. So the enter button event will be triggered.
Instead of return false use event.returnValue = false.
Try changing all the instances of
$(field).functionCall()
to
field.functionCall()
since field is already a jQuery object.
Ok now we've established that this wasn't the error. I tested in Firefox 7 and Chrome 15 and saw that the code block in the if statement is only fired once when enter is pressed. Try checking to make sure that something inside the createTag() function isn't doing something twice.
What do you think is catching the event when it bubbles. I only get one firing with this test page.
<!DOCTYPE html>
<html>
<head>
<title>Scratch</title>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.setOnLoadCallback(function (){
$('input[type="text"]').keyup(function (){
console.debug('keyup');
});
});
google.load('jquery', '1.6.4');
</script>
</head>
<body>
<div class="something">
<input type="text" />
</div>
</body>
</html>
Maybe it's your selector. Is it nested inside another .addTag? When I change the jQuery selector and also make the div and input the same class I start to get two events firing. Like this:
$('.thing').show().keyup(...);
...and...
<div class="thing">
<input class="thing" type="text" />
</div>
This is a problem which always drives me insane but i think this is the solution
simply return false, if you return true it repeats it self randomly so im guessing it must have a listener which listens out for true responses.
Short Answer
Add return false;
$("#register-form #first_name").keyup(function(event) {
console.log('hello world');
return false;
});
in the original question if you look at the code closely is seems the return false was written one line too early.
I had this issue using Angular 11 EventEmitters. I solved it by creating a new instance of my event emitter whenever the
event is triggered.
#Output() keypress = new EventEmitter();
onKeyPress(event) {
this.keypress = new EventEmitter();
this.keypress.emit(event);
}
I passed through the same and this structure worked for me:
const onKeyPress = (e: React.KeyboardEvent): void => {
if (onSubmit && e.key.toLowerCase() === 'enter') {
onSubmit();
e.stopPropagation();
e.preventDefault();
}
};
Related
I have some code which has some conditional branches if the FocusEvent has been triggered through a mouseclick outside of the input-box or if it has been tabbed out. It's pretty messy JS-Legacy code and I only have time to apply a hotfix here.
Doc for FocusEvent: https://developer.mozilla.org/en/docs/Web/API/FocusEvent
Unlike the Click event the FocusEvent does not have any informations about buttons pressed during the event triggering.
Does anybody has an idea how I can get this information? Via Google I only found workarounds - but I just can't believe that this FocusEvent has a way to receive the button pressed out of the box?
FocusEvent is clearly described as an experimental technology in the doc you linked. So what you ask may be added in the future. But for now it looks like you have no other choice but to use a workaround.
I made one to try:
var clickWhileFocused = false;
$("#testInput").on("tabbedOut", function () {
console.log("tabbedOut");
});
$("#testInput").on("clickedOut", function () {
console.log("clickedOut");
});
$(document).on("mousedown", function (e) {
if($("#testInput").is(":focus") && e.target.id != "testInput") {
$("#testInput").trigger("clickedOut");
clickWhileFocused = true;
}
});
$("#testInput").on("focusout", function () {
if(!clickWhileFocused) {
$("#testInput").trigger("tabbedOut");
}
clickWhileFocused = false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text"/>
<input id="testInput" type="text" placeholder="#testInput"/>
<input type="text"/>
I've gotten hundreds of aids from this site. thanks. This is my first question.
Which object is a modal window (alert popup) into the Dom. How can i refer it? How can i know if open or closed? Something like this: if (alertPopup is open) {..code...}
My code is this (i use jQuery):
<script type="text/javascript">
$(document).ready(function(){
var myButton = $('#mybutton')
myButton.click(function(){
if ($('#myinput').val() == '') {
alert('input Empty!');
} else {
// More code.
}
});
$(document).keyup(function(e){
if (e.keyCode == 13) myButton.trigger('click');
})
});
</script>
<body>
<input id="myinput" />
<button id="mybutton">Show alert</button>
</body>
The purpose of the code is trigger up the event 'click' on the button whith key 'enter'. It works, but when i close the popup, again with key 'enter', the popup comes again an again. I need to disable event 'click' of my button or unbind the trigger action when the popup is displayed.
I would't like to make my own modal windows.
thanks in advance.
You can move the handler to its own function and programmatically bind/unbind it to the event:
$(document).ready(function(){
var myButton = $('#mybutton')
console.log('whee');
myButton.click(clickHandler);
$(document).keyup(function(e){
if (e.keyCode == 13) myButton.trigger('click');
})
});
function clickHandler(){
$('#mybutton').unbind('click', clickHandler)
if ($('#myinput').val() == '') {
alert('input Empty!');
} else {
// More code.
}
}
However, it looks more like you're trying to deal with enter buttons in a form submission style. I'd recommend wrapping this whole thing in a form and dealing with it as such.
See http://jsfiddle.net/ruBY4/ for a cleaner form-based solution.
Is there any event in Jquery that's triggered only if the user hits the enter button in a textbox? Or any plugin that can be added to include this? If not, how would I write a quick plugin that would do this?
You can wire up your own custom event
$('textarea').bind("enterKey",function(e){
//do stuff here
});
$('textarea').keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterKey");
}
});
http://jsfiddle.net/x7HVQ/
$('#textbox').on('keypress', function (e) {
if(e.which === 13){
//Disable textbox to prevent multiple submit
$(this).attr("disabled", "disabled");
//Do Stuff, submit, etc..
//Enable the textbox again if needed.
$(this).removeAttr("disabled");
}
});
Here is a plugin for you: (Fiddle: http://jsfiddle.net/maniator/CjrJ7/)
$.fn.pressEnter = function(fn) {
return this.each(function() {
$(this).bind('enterPress', fn);
$(this).keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterPress");
}
})
});
};
//use it:
$('textarea').pressEnter(function(){alert('here')})
heres a jquery plugin to do that
(function($) {
$.fn.onEnter = function(func) {
this.bind('keypress', function(e) {
if (e.keyCode == 13) func.apply(this, [e]);
});
return this;
};
})(jQuery);
to use it, include the code and set it up like this:
$( function () {
console.log($("input"));
$("input").onEnter( function() {
$(this).val("Enter key pressed");
});
});
jsfiddle of it here http://jsfiddle.net/VrwgP/30/
It should be well noted that the use of live() in jQuery has been deprecated since version 1.7 and has been removed in jQuery 1.9. Instead, the use of on() is recommended.
I would highly suggest the following methodology for binding, as it solves the following potential challenges:
By binding the event onto document.body and passing $selector as the second argument to on(), elements can be attached, detached, added or removed from the DOM without needing to deal with re-binding or double-binding events. This is because the event is attached to document.body rather than $selector directly, which means $selector can be added, removed and added again and will never load the event bound to it.
By calling off() before on(), this script can live either within within the main body of the page, or within the body of an AJAX call, without having to worry about accidentally double-binding events.
By wrapping the script within $(function() {...}), this script can again be loaded by either the main body of the page, or within the body of an AJAX call. $(document).ready() does not get fired for AJAX requests, while $(function() {...}) does.
Here is an example:
<!DOCTYPE html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var $selector = $('textarea');
// Prevent double-binding
// (only a potential issue if script is loaded through AJAX)
$(document.body).off('keyup', $selector);
// Bind to keyup events on the $selector.
$(document.body).on('keyup', $selector, function(event) {
if(event.keyCode == 13) { // 13 = Enter Key
alert('enter key pressed.');
}
});
});
</script>
</head>
<body>
</body>
</html>
If your input is search, you also can use on 'search' event. Example
<input type="search" placeholder="Search" id="searchTextBox">
.
$("#searchPostTextBox").on('search', function () {
alert("search value: "+$(this).val());
});
//Short and simple solution
$(document).ready(function(){
$('#TextboxId').keydown(function(event){
if (event.which == 13){
//body or action to be performed
}
});
});
HTML Code:-
<input type="text" name="txt1" id="txt1" onkeypress="return AddKeyPress(event);" />
<input type="button" id="btnclick">
Java Script Code
function AddKeyPress(e) {
// look for window.event in case event isn't passed in
e = e || window.event;
if (e.keyCode == 13) {
document.getElementById('btnEmail').click();
return false;
}
return true;
}
Your Form do not have Default Submit Button
Another subtle variation.
I went for a slight separation of powers, so I have a plugin to enable catching the enter key, then I just bind to events normally:
(function($) { $.fn.catchEnter = function(sel) {
return this.each(function() {
$(this).on('keyup',sel,function(e){
if(e.keyCode == 13)
$(this).trigger("enterkey");
})
});
};
})(jQuery);
And then in use:
$('.input[type="text"]').catchEnter().on('enterkey',function(ev) { });
This variation allows you to use event delegation (to bind to elements you haven't created yet).
$('body').catchEnter('.onelineInput').on('enterkey',function(ev) { /*process input */ });
I could not get the keypress event to fire for the enter button, and scratched my head for some time, until I read the jQuery docs:
"The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events." (https://api.jquery.com/keypress/)
I had to use the keyup or keydown event to catch a press of the enter button.
<form name="searchForm" id="searchForm" onsubmit="doSomething(event)">
<input type="text" name="search" id="search">
</form>
<script>
function doSomething(event){
let $val = $('form#searchForm input[name="search"]').val();
console.log($val);
event.preventDefault();
}
</script>
One simple way it can be done in this way. Enter text or number, hit enter key and get the entered input value.
I have a blur function already attached to my dropdown, now I want to call another function onchange after my blur function is called in javasript.
<select onchange="CheckAccommodation(this)" onblur="return UpdateFormSelect('UpdatePrice.aspx', 'BookNow_accommodation1', 'select', 'BookNow_accommduration');javascript:test()" id="BookNow_accommodation1" name="BookNow:accommodation1">
Now I want to call my javascript:test() after the blur is done
Please suggest!
Thanks.
Best Regards,
Yuv
This suggested by #Ghommey will work:
<select onchange="CheckAccommodation(this)" onblur="return
UpdateFormSelect('UpdatePrice.aspx', 'BookNow_accommodation1',
'select', 'BookNow_accommduration');test()" id="BookNow_accommodation1"
name="BookNow:accommodation1">
it works irrespective of what you return from UpdateFormSelect.
function onChangeHandler(){
//.........
}
$("SELECT_ID").blur(function(){
//handle blur
//call on change handler
onChangeHandler();
});
Now I want to call my javascript:test() after the blur is done
Then just remove the ‘return’ on the first statement, allowing it to fall through to the second:
onblur="UpdateFormSelect('UpdatePrice.aspx', 'BookNow\_accommodation1', 'select', 'BookNow\_accommduration');test()"
You could put return test(), but actually onblur doesn't need to return anything. <a onclick> often needs to return false to stop the link being followed, but other than that you often don't need any return value from an event handler.
It's also a bit of a mouthful to put in an event handler. You might benefit by breaking the JavaScript out:
<select id="BookNow_accommodation1" name="BookNow:accommodation1">
...
</select>
<script type="text/javascript">
var acc1= document.getElementById('BookNow_accommodation1');
acc1.onchange= function() {
CheckAccommodation(this);
// or just move the body of CheckAccommodation here
};
acc1.onblur= function() {
UpdateFormSelect('UpdatePrice.aspx', 'BookNow_accommodation1', 'select', 'BookNow_accommduration');
test();
};
</script>
How do you detect which form input has focus using JavaScript or jQuery?
From within a function I want to be able to determine which form input has focus. I'd like to be able to do this in straight JavaScript and/or jQuery.
document.activeElement, it's been supported in IE for a long time and the latest versions of FF and chrome support it also. If nothing has focus, it returns the document.body object.
I am not sure if this is the most efficient way, but you could try:
var selectedInput = null;
$(function() {
$('input, textarea, select').focus(function() {
selectedInput = this;
}).blur(function(){
selectedInput = null;
});
});
If all you want to do is change the CSS for a particular form field when it gets focus, you could use the CSS ":focus" selector. For compatibility with IE6 which doesn't support this, you could use the IE7 library.
Otherwise, you could use the onfocus and onblur events.
something like:
<input type="text" onfocus="txtfocus=1" onblur="txtfocus=0" />
and then have something like this in your javascript
if (txtfocus==1)
{
//Whatever code you want to run
}
if (txtfocus==0)
{
//Something else here
}
But that would just be my way of doing it, and it might not be extremely practical if you have, say 10 inputs :)
I would do it this way: I used a function that would return a 1 if the ID of the element it was sent was one that would trigger my event, and all others would return a 0, and the "if" statement would then just fall-through and not do anything:
function getSender(field) {
switch (field.id) {
case "someID":
case "someOtherID":
return 1;
break;
default:
return 0;
}
}
function doSomething(elem) {
if (getSender(elem) == 1) {
// do your stuff
}
/* else {
// do something else
} */
}
HTML Markup:
<input id="someID" onfocus="doSomething(this)" />
<input id="someOtherID" onfocus="doSomething(this)" />
<input id="someOtherGodForsakenID" onfocus="doSomething(this)" />
The first two will do the event in doSomething, the last one won't (or will do the else clause if uncommented).
-Tom
Here's a solution for text/password/textarea (not sure if I forgot others that can get focus, but they could be easily added by modifying the if clauses... an improvement could be made on the design by putting the if's body in it's own function to determine suitable inputs that can get focus).
Assuming that you can rely on the user sporting a browser that is not pre-historic (http://www.caniuse.com/#feat=dataset):
<script>
//The selector to get the text/password/textarea input that has focus is: jQuery('[data-selected=true]')
jQuery(document).ready(function() {
jQuery('body').bind({'focusin': function(Event){
var Target = jQuery(Event.target);
if(Target.is(':text')||Target.is(':password')||Target.is('textarea'))
{
Target.attr('data-selected', 'true');
}
}, 'focusout': function(Event){
var Target = jQuery(Event.target);
if(Target.is(':text')||Target.is(':password')||Target.is('textarea'))
{
Target.attr('data-selected', 'false');
}
}});
});
</script>
For pre-historic browsers, you can use the uglier:
<script>
//The selector to get the text/password/textarea input that has focus is: jQuery('[name='+jQuery('body').data('Selected_input')+']')
jQuery(document).ready(function() {
jQuery('body').bind({'focusin': function(Event){
var Target = jQuery(Event.target);
if(Target.is(':text')||Target.is(':password')||target.is('textarea'))
{
jQuery('body').data('Selected_input', Target.attr('name'));
}
}, 'focusout': function(Event){
var Target = jQuery(Event.target);
if(Target.is(':text')||Target.is(':password')||target.is('textarea'))
{
jQuery('body').data('Selected_input', null);
}
}});
});
</script>
You only need one listener if you use event bubbling (and bind it to the document); one per form is reasonable, though:
var selectedInput = null;
$(function() {
$('form').on('focus', 'input, textarea, select', function() {
selectedInput = this;
}).on('blur', 'input, textarea, select', function() {
selectedInput = null;
});
});
(Maybe you should move the selectedInput variable to the form.)
You can use this
<input type="text" onfocus="myFunction()">
It triggers the function when the input is focused.
Try
window.getSelection().getRangeAt(0).startContainer