Binding enter key conflicts with alert popup [duplicate] - javascript

This question already has an answer here:
How to stop alert box press enter loop?
(1 answer)
Closed 9 years ago.
When the user presses the Enter key anywhere on the body, it triggers the click event on another element which in turn opens a basic alert popup (for testing purposes).
This creates a loop because pressing Enter again will close the alert but will trigger the event again, opening a new alert, and the cycle repeats.
I'm using this in a modal box script. When the modal box appears, the user can press Enter to perform the action that a button inside the modal box would do, such as closing it (or in my case, opening an alert popup).
The click code:
//Add click events...
button.bind('click', mybtn, function(e) {
var click;
if (e.data.onclick) {
e.data.onclick(e);
} else if (e.data.click) {
e.data.click(e);
}
});
The key code:
//Add key events...
$('body').keyup(mybtn, function(e) {
var keyCode = e.keyCode || e.which;
//What key we need to match...
switch (e.data.key) {
case 'enter':
if (keyCode == 13) e.data.button.trigger('click');
break;
case 'esc':
case 'escape':
if (keyCode == 27) e.data.button.trigger('click');
break;
}
});
Should I bind my events in a different place (element)? Is there a better way to bind to stop this loop?
I can't unbind the key event because my script needs to be flexible enough to handle multiple key presses.
Example of creating a modal box:
createModal('HTML <b>content</b>', [{ label: 'Close', onclick: function() { alert('Modal closed'); }, key: 'enter' }]);
The HTML content is dumped into the modal, then the function will loop through the controls you've defined and will try to build them for you. In this example you define a "close" control, which would look like this (if you used onclick=""):
<button onclick="function() { alert('Modal closed'); }">Close</button>
with an event assigned to the document that when you press Enter it will trigger clicking that button, causing the problem.

button.one('click', mybtn, function(e) {
var click;
if (e.data.onclick) {
e.data.onclick(e);
} else if (e.data.click) {
e.data.click(e);
}
});
Will limit the click event to only one occurrence and then it unbinds itself.

Related

Extjs 4 event stop propagation not working

I am using Extjs 4 and overriding a Ext.util.Observable as the name Ext.tree.Search. In the extended class I have implemented event listener onTriggerSearch so when the user types some words in input and presses enter key, this function is get called and do some search job. The search plugin has a view like the image below:
If the user submit the search by pressing magnifier icon, everything goes right but if press enter key, after doing the search, the page gets refreshed. How should I catch this event (key press event) completely and stop propagating. The thing I have tested by now is lines below:
, onTriggerSearch: function (a, event, c) {
// stop event propagation
if (event.browserEvent.stopPropagation)
event.browserEvent.stopPropagation();
if (event.browserEvent.cancelBubble != null)
event.browserEvent.cancelBubble = true;
// event.browserEvent.bubbles = false;
// event.browserEvent.cancelBubble = true;
// event.browserEvent.stopPropagation();
// ======================
... some other jobs
return false; // to stop propagation
}
There was some weeks I had trouble with this issue and by now I have discovered that the problem is with the form containing this input. I have prevented form to submit using these answers:
How to prevent ENTER keypress to submit a web form?
Done.

Change event is fired once for a select if dialog is escaped or clicked out side

I am trying to write this simple Javascript logic to disable multiselect field if user chose specific options from another select field. This is a JIRA dialog2, so I am using their JQuery namespace (eg: AJS).
Problem is when I open the dialog and select the specific values from the select field the handler for the change event of the select field runs properly and the other multiselect field is disabled. However, the snippet is not called/doesn't run if the dialog got closed by either pressing escape button or clicking outside it, as opposed to closing it by clicking the 'close' button. I am not a js expert and would appreciate any help in this.
(function($) {
$(function() {
AJS.dialog2.on("show", function(e) {
var targetId = e.target.id;
var spinning = false;
if (targetId == "sr-dialog") {
//start of the part that fails
//noticing that the change event for the searchtypeselect field is fired only when the dialog shows up first time and re shows again only if the dialog got closed by the 'close' button. If dialog escaped it doesn't fire anymore.
var $searchTypeSelect = AJS.$("#select-searchtype");
var $fieldMultiSelect = AJS.$("#field-multiselect");
$searchTypeSelect.change(function(e) {
if ($searchTypeSelect.val() == 'D' || searchTypeSelect.val() == 'S') {
$fieldMultiSelect.removeAttr('disabled');
} else {
$fieldMultiSelect.attr('disabled', 'disabled').val('');
}
}).trigger('change');
// end of the part that fails
AJS.$(e.target).find("#submit-spinner-trigger").click(function(e) {
var number = AJS.$("input[type=radio]:checked", "#topSearchForm").val();
var searchType = AJS.$("#select-searchtype option:selected", "#topSearchForm").val();
var fields = [];
AJS.$("#field-multiselect :selected", "#topSearchForm").each(function(i, selected) {
fields[i] = $(selected).val();
});
var since = AJS.$("#select-since option:selected", "#topSearchForm").val();
if (!spinning) {
AJS.$('.button-spinner').spin();
spinning = true;
}
});
}
});
});
})(AJS.$);
I don't think this is related to JIRA or AUI. It's just a javascript question.
You'd like to handle an event when a dialog gets 'closed' by clicking 'escape' or the 'x' at the top. These posts answer that:
Hook into dialog close event
How to handle ESC keydown on javascript popup window
Thanks GlennV. It is that actually and also hooking the event handler to the specific item on the screen helped fix the issue.
Answered here

Event listener doesn't work for Enter key

What may be the reason, that event listener of Enter key doesn't work?
I tried both plain JS:
addEventListener("keydown", function (e) {
if (e.keyCode === 13) {
enter(e);
}
});
function enter(e) {
event.preventDefault();
alert("You pressed enter");
}
and jQuery:
$(document).keypress(function(e) {
if(event.which == 13) {
event.preventDefault();
alert('You pressed enter!');
}
});
Also, I tried both event and e. Doesn't work. For another key, for example Backspace it works well.
That is a plugin for our corporate intranet - when you click some letter in email inbox, and after that press Enter, small pop-up window must be shown. But for some reason Enter is ignored in my script - instead of showing pop-up, webpage immediately opens the letter (that is a default behavior).
As I understand, the reason may be in another listener somewhere in webmail interface? Or not? If yes, may I somehow impart higher priority for handling Enter (so, before opening the letter, pop-up will be shown)?
Apologize for long description.
It should work as long as you bind the event handler within the document.ready
$(function(){
$(document).keypress(function(e) {
if(event.which == 13) {
event.preventDefault();
alert('You pressed enter!');
}
});
});
Here is a working sample

Need to assign an event listener to the tab key using keycodes in JavaScript?

I have currently an eventlistener listening for when a user enters an email address in a textbox on an html website. It then displays an alert when it detects an email address is being entered. Currently I have set it up whereby it detects the event blur then checks whether it meets the regex then an alert will display. This creates many alerts and is not very accurate as the alert
I need the eventlistener to listen for when the tab key specifically is pressed. I know I need to use KeyCodes but have not used them before. This eventlistener is currently working dynamically as it is a Firefox AddOn that scans a webpage so the eventlistener is not specifically attached to a specific input box.
Code:
vrs_getWin.document.getElementsByTagName("body")[0].innerHTML = bodyContents;
var inputFields = vrs_getWin.document.getElementsByTagName("input");
for(inputC=0; inputC < inputFields.length; inputC++) {
var elementT = inputFields[inputC].getAttribute("id");
inputFields[inputC].addEventListener("blur", function(){
var emailPattern = /(\w[-._\w]*\w#\w[-._\w]*\w\.\w{2,3})/g;
var resultEmail = emailPattern.test(vrs_getWin.document.getElementById(elementT).value);
if(result) {
prompts.alert(null, "Test", vrs_getWin.document.getElementById(elementT).value);
}
}, false);
}
Any help with this will be much appreciated.
I think from a UX stand point, I would not recommend using a javascript alert to notify the user of a problem, especially if you want the notification to happen when they have completed a single form input. The blur event would be my recommendation, and use some other visual cue to notify the user.
But, if you want to go with the tab key, the event your looking for is 'keydown', or 'keyup'. To use it you listen for the keydown event then check if the event.keyCode == '9'. (tab key)
document.addEventListener('keydown', function(e){
if( e.keyCode == '9' ){
alert('You pressed the tab key.');
}
}, false);
To get the keycodes of keys I like to pop open a console and type in:
document.addEventListener('keydown', function(e){
console.log( e.keyCode );
}, false);
Then when you press a key, it will output the keycode for that key.

Trigger an event on click within body area

I need to trigger the click, on click on my webpage. I tried the below and it triggers the click onload and not on click.
$(function() {
$("body").click(function(e) {
alert("code");
})
$('#container').trigger('click');
});
Basically I need to show a popup on click of P keyword from keyboard. While I started I got stuck during the initial stages. Not sure how to achieve this.
I guess you need a keydown event where P key passes ASCII code 80:
$("body").on("keydown", function(e) {
if (e.which === 80) {
alert("'p' was pressed");
}
});

Categories

Resources