I am trying to create a Drop down list, that when a user holds the SHIFT key, it will select the same index on all other drop down lists.
Currently, I am doing the following:
$(document).on('keyup keydown', function (e) { shifted = e.shiftKey });
$(document).on('change', '.report_info select', function (e) {
if (shifted) {
//Code to change other drop down lists.
}
});
This only works if you press and hold the shift key before you enter the drop down list. If you are inside the DDL and press the shift key, the keyup/keydown event will not fire and shifted will remain false
Is there any way to catch the keyup/keydown event while a dropdownlist is focused?
Edit:
Looks like it might be an issue with Chrome only, Just tried adding the following, and it works in Firefox and IE, but not Chrome:
$(document).on('keyup keydown', 'select', function (e) {
shifted = e.shiftKey;
});
Here is a fiddle of it not working in chrome: http://jsfiddle.net/ue6xqm1q/4
I think #judgeja's response may be your best bet. I'm posting this as an "answer" instead of a comment, because I've done my own research to determine that absolutely no event gets fired when a select element is open in Chrome.
See Fiddle: http://jsfiddle.net/m4tndtu4/6/
I've attached all possible event handlers (I think) to the input element and both select elements.
In Chrome, you'll see many events fire when working with the input element, but you'll see no events fire when working in the first select element when it is open.
Interestingly, events do fire in Chrome if the select element has the multiple attribute or size>1.
In Firefox, you'll see events firing on all three elements.
Outside #judgeja's suggestion, your best bet may be to simulate the select element.
UPDATE
Warning: Chrome (mis)behavior differs on different platforms! In Chrome Windows a keydown event is triggered right after the select is released, while on OsX it is not. This explains why #judgeja solution worked for some, and didn't for me, while mine worked on OsX and not on Windows.
So I created an updated fiddle to merge my OsX solution with his Windows one.
http://jsfiddle.net/0fz5vcq6/5/
On platforms where the keydown is triggered uses #judgeja solution, if it is not triggered it tests for a keyup event without the previous keydown (my previous solution). It is ugly as it works only after RELEASE of the shift key, but ugly only on Chrome OsX.
var shifted = false;
var hackytimer = 0;
var lastval=null;
$(document).keydown(function(e){
if(e.which == 16){
if(Date.now() - hackytimer <200){
alert("you pressed shift inside the select (Win)");
changeAllSelects($(this).val());
} shifted = true;
}
});
$(document).keyup(function(e){
if(e.which == 16) {
if(!shifted && lastval!=null) {
alert("you pressed shift inside the select (OsX)");
$('.report_info select').each(function () {
changeAllSelects(lastval);
});
}
shifted = false;
}
});
$(document).on('change', '.report_info select', function (e) {
hackytimer = Date.now();
if (shifted) {
changeAllSelects($(this).val());
} else {
lastval=$(this).val();
}
});
function changeAllSelects(cr){
hackytimer = 0;
$('.report_info select').each(function () {
$(this).val(cr);
});
}
Credit goes mainly to #judgeja for his timer solution with some added workaround for the Mac (and other platforms that behave the same)
I still think emulating the selects with something HTML like http://gregfranko.com/jquery.selectBoxIt.js/ is cleaner as they should not interfere with keydown/keyups.
PREVIOUS SOLUTION (OsX only)
The only solution I could think of, in the total absence of any event, is to test if a shift up occurred without the previous shift down. This may work if you don't have other elements that behave the same way as the selects
http://jsfiddle.net/6jkkgx5e/
It is a bit tricky and dirty, will work AFTER the user releases the shift key
var shifted = false;
var lastval=null;
$(document).keydown(function(e){
if(e.which == 16){
shifted = true;
}
});
$(document).keyup(function(e){
if(e.which == 16){
if(!shifted && lastval!=null) {
alert("you pressed shift inside the select");
$('.report_info select').each(function () {
$(this).val(lastval);
});
}
shifted = false;
}
});
$(document).on('change', '.report_info select', function (e) {
var cr = $(this).val();
if (shifted) {
$('.report_info select').each(function () {
$(this).val(cr);
});
} else {
lastval=cr;
}
});
Should behave normally on non buggy browsers. Anyway I agree emulating the selects with something HTML like http://gregfranko.com/jquery.selectBoxIt.js/ might be the cleaner way.
Your syntax looks incorrect.
$("#target").keydown(function() {
alert( "Handler for .keydown() called." );
});
This is a pretty hacky solution to be honest, but it's a means to an ends until you hopefully find something better.
Since the problem is chrome doesn't register the keydown/keyup events on the select elements until after the dropdownlist has disappeared, we need to either
a) figure out how to make the event fire (I've no idea)
or
b) check if our conditions were met in a different order.
Chrome will fire the shift keypress event after click, so we can simply check if click was pressed immediately before this event. Since other browsers behave more expectedly we'll also leave the previous code in place.
To do this we set a timer on the click event, and then when the shift event for the select is fired, if the click event timer was also just set we should run our code here so that chrome will fire it. We reset the timer then so that it isn't fired multiple times.
NOTE: if you press shift immediately after setting the values (within whatever limit from the click you specify), it will also set them all. I don't think this is unreasonable as it actually feels quite natural when it happens.
I used the following code:
var shifted = false;
var hackytimer = 0;
$(document).on('keyup keydown', function (e) {
shifted = e.shiftKey;
});
$(document).on('keyup keydown', 'select', function (e) {
shifted = e.shiftKey;
if(Date.now() - hackytimer <200){
changeAllSelects($(this).val());
}
});
$(document).on('change', '.report_info select', function (e) {
hackytimer = Date.now();
if (shifted) {
changeAllSelects($(this).val());
}
});
function changeAllSelects(cr){
hackytimer = 0;
$('.report_info select').each(function () {
$(this).val(cr);
});
}
See working example here: http://jsfiddle.net/0fz5vcq6/2/
First of all. You should pick an event to register. Don't register to keyup and keydown the same time. You give the browser a hard time, because they affect your end result. To see what I mean, just edit the plunk, add a keyup event. The end result behaves a little sloppy.
keyup: Event fired when a key is released on the keyboard.
keydown: Event fired when a key is pressed on the keyboard.
keypress: Event fired when a key is pressed on the keyboard.
They have their differences, better stick to one, I prefer for this example to use keydown, just plays better with me, you can use keyup.
Edit: A quick note. The keyup for my example doesn't play well, because it seems, change in the selectedIndex, comes first and then the binded event. On keydown, first the event fires, does it's work and then the selectedIndex changes. To play with keyup, the code below needs some modification, that means the step is not needed, when you use keyup
I have a plnkr demo here.
I've tested it on IE10, Opera, Safari, Firefox and Chrome. As you might expect, webkit browsers, don't fire the keydown/keyup/keypress event when a select list has focus. Reason unknown for me, at the moment. In Firefox works great. On IE works partially. So, in order to achieve your goal, custom code to the rescue! I just binded a change event to the document, i hear for kewdown and change. If the event type is change, then the workaround comes into play. Here some code:
$(document).ready(function(){
$(document).on('keydown change', 'select', function(evt){
var shiftKey = evt.shiftKey;
var code = evt.keyCode || evt.which;
//if it's a change event and i dont have any shiftKey or code
//set the to a default value of true
if(evt.type === 'change' && !shiftKey && !code){
//special! only when change is fired
shiftKey = true;
code = true;
}
//if shift key
if(shiftKey && (code === 40 || code === 38 || code === true)){
var target = $(evt.target);
//if code is not true means it is not a change event, go ahead and set
//a step value, else no step value
var step = (code !== true) ? (code === 40) ? 1 : -1 : 0;
var index = target[0].selectedIndex + step;
//just to keep the lower and upper bound of the select list
if(index < 0){
index = 0;
}else if(index >= target[0].length){
index = target[0].length - 1;
}
//get all other select lists
var allOtherSelects = target.closest('div').siblings('div').children('select');
//foreach select list, set its selectedIndex
$.each(allOtherSelects, function(i, el){
el.selectedIndex = index;
});
}
});
});
Chrome hack: You can set custom event for document. And firing this event when press the shift key inside the DDL. Jquery firing trigger can pass custom params.
Check the working JS FIDDLER
Try the following script for your scenario
<script type="text/javascript" language="javascript">
window.shifted = false;
$(document).on('keyup keydown', function (e) { shifted = e.shiftKey; });
$(document).on('change', 'select.report_info', function (e) {
var cr = $(this).val();
if (shifted) {
$('.report_info').each(function () {
$(this).val(cr);
});
}
});
</script>
Bryan,
you can try the following way to do this. I tested on Jsfiddle it working in your way If I got your question correctly.
var shifted = false;
$(document).on('keyup keydown', function (e) { shifted = e.shiftKey; });
$("select").on('keyup keydown', function (e) {
shifted = e.shiftKey;
});
$('.report_info select').on('change', function (e) {
var cr = $(this).val();
if (shifted) {
$('.report_info select').each(function () {
$(this).val(cr);
});
}
});
Please let me know if it works for you.
Hello that was not working because of no focus on your select which has keydown bound
try this
http://jsfiddle.net/t8fsuy33/
$('select').first().focus();
Hop this thing help you out.. :)
var onkeydown = (function (ev) {
var key;
var isShift;
if (window.event) {
key = window.event.keyCode;
isShift = window.event.shiftKey ? true : false;
} else {
key = ev.which;
isShift = ev.shiftKey ? true : false;
}
if ( isShift ) {
switch (key) {
case 16: // ignore shift key
break;
default:
alert(key);
// do stuff here?
break;
}
}
});
I found a very unique solution to this issue specifically for Chrome. It appears Chrome shifts outside the normal dom for select elements when they have focus so you never get the onkey(down|press|up) events to capture the keycode. However if the size of the select box is >1 then it works. But anyone who wants an actual drop down box instead of what looks like a combo box can solve this issue with this code. In my case I was trying to prevent the backspace key from going back to the previous browser page.
Javascript looks like this:
$(document).ready(function() {
$('select').keypress(function(event)
{ return cancelBackspace(event) });
$('select').keydown(function(event)
{ return cancelBackspace(event) });
});
function cancelBackspace(event) {
if (event.keyCode == 8) {
return false;
}
}
Then HTML looks like this:
<select id="coaacct" style="border:none;width:295px;" onclick="if (this.size){this.size=''}else{this.size='20'};">
I use the onclick event to change the size of the select box to 20 if it has no size and change it back to nothing if it has a size. This way it functions like a normal select dropdown but because it has a size greater than 1 when you are selecting the option it will detect keycodes. I didn't see this answered adequately anywhere else so I thought I would share my solution.
If you need to do things with a dropdown that are this granular, it's likely not worth it to use the native <select> element as-is. In this thread alone, numerous implementation differences are discussed, and there are plenty more that are outside the scope of this discussion but will also likely affect you. There are several JS libraries that can wrap this control, leaving it as-is on mobile (where the native control is actually needed) but emulating it on desktop, where the control doesn't really do much that can't be emulated in JS.
bootstrap - doesn't automatically wrap native control for mobile
dropdown.js
dropdown.dot.js
Related
I have a function in js which accepts only floating number, in which regex of floating number is being tested
$(document).ready(function () {
$(".validate-foating-value").keypress(function (e) {
if (!/^[0-9]*\.?[0-9]*$/.test($(e.target).val() + String.fromCharCode(e.which))) {
return false;
}
});
});
its working fine in chrome in Firefox as well but problems I am facing through Firefox are
backspace not working
arrow keys not working
shift+arrow keys for selection and Ctrl+A not working
here is the fiddle.
any other work around for FLOATING numbers?
You can hack something like:
$(document).ready(function () {
$(".validate-foating-value").keypress(function (e) {
var keyCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
if (!/^[0-9]*\.?[0-9]*$/.test($(this).val() + String.fromCharCode(keyCode)) && keyCode!=8) {
return false;
}
});
});
Please let me know if it works for you.
Thanks
I changed your Javascript/JQuery code to
$(document).ready(function () {
$(".validate-foating-value").bind('input propertychange', function () {
if (!/^[0-9]*\.?[0-9]*$/.test($(this).val())) {
var currentVal = $(this).val();
$(this).val(currentVal.slice(0,-1));
}
});
});
There is one issue with keypress that's documented here, namely this event is not consistently fired across browsers (for instance backspace does not trigger a keypress on Chrome).
I tried using keyup in place of keypress but I couldn't figure out how to detect the fact that the keyboard event was producing some input. I thought of using the JQuery .change on the input box but this event is not fired every time a key is pressed but only when the elements loses focus.
So in the end I I found a solution in the accepted answer to Validate html text input as it's typed
Please let me know if this helps.
http://jsfiddle.net/user2314737/b85k3zbh/10/
This question has been asked plenty of times before, but no answers I have found seem to solve my problem.
From a classic asp page I call a Javascript function
on each of my pages. The point is to fire a search button when a user enters search text and presses enter, rather than clicking on the button, or choosing from the Ajax provided selections.
This works fine in IE and FF, as has been the case for every other question asked along these lines.
Here is the Javascript. Can anybody tell me please how to have it work for Chrome as well as IE and FF ?
Edited following answer form Alexander O'Mara below:
Altered function call in body tag on page to use onkeyup instead of onkeypress - onkeyup="KeyPress(event)"
Altered JS function (also after heeding comments re duplication from others - thanks) as follows:
function KeyPress(e)
{
var ev = e || window.event;
var key = ev.keyCode;
if(window.event) // IE
{
key = e.keyCode;
if (key == 13)
{
window.event.keyCode = 0;
$('#btnSearch').click();
}
}
else if (key == 13)
{
btnSearch.click();
ev.preventDefault();
}
}
It seems to work sometimes and not others, and rarely on chrome currently. Is there a guaranteed way to have it work all the time ?
The main page of my site if you want to try it yourself is www.dvdorchard.com.au, your cursor will be sitting in the search box on arrival - enter a word > 3 chars and press enter, if you stay on the page it didn't work, if you move to the productfound.asp page it worked.
Thanks again.
You are looking for the keyup event (documentation). The keypress event is not consistent across browsers. See this question for information on the differences.
Update:
Since you are using jQuery, you can also remove the onkeyup="KeyPress(event)" attribute for you body, and replace your KeyPress function with the following (replacing the contents with your event handling code).
$(window).keyup(function(e){
/*YOUR CODE HERE*/
});
if(e.keyCode)
{
key= e.keyCode;
}
else
{
key = e.charCode;
}
Fire your event with onkeyup
read more
this should work in chrome. I don't know about other browsers
function code(e) {
e = e || window.event;
return(e.keyCode || e.which);
}
window.onload = function(){
document.onkeypress = function(e){
var key = code(e);
// do something with key
// done doing something with key
key=0
};
};
How can I find out a HTML-Element (lets say a select-tag) got focus by mouse-click, keyboard or JavaScript function?
<select onfocus="foo(event)"></select>
<script>
function foo(e) {
if (e.??? == 'mouse') {
//do something
}
else if (e.??? == 'keyboard') {
//do something different
}
}
</script>
I also tried to add an onclick event to the element but the onfocus event fires first.
I don't believe there is any native way to see how the element received its focus (correct my if I'm wrong!).
However, you may be able to do something like store when the mouse is clicked, store when the keyboard is used and then react based on the last active state.
var inputState = null;
document.addEventListener("click", handleClick);
document.addEventListener("keyup", handleKey);
function handleClick () {
inputState = "mouse";
}
function handleKey () {
inputState = "keyboard";
}
function foo() {
if ( inputState === "mouse" ) {
// mouse code
} else if ( inputState === "keyboard" ) {
// keyboard code
} else {
// Function was called directly
}
// Reset input State after processing
inputState = null
}
This will likely need some adjustments but I hope you can use this to find the correct answer.
Edit:
My answer is a vanilla JS solution, if you have access to jQuery you may want to investigate the click and keyup event handlers.
Use document.activeElement, it is supported in all major browsers. It can give you the current active element.
EDIT
Oops I think I misunderstood your question. you want to identify the mouse or keyboard or programmatic
For programmatic
if(e.hasOwnProperty('originalEvent')) {
// Focus event was manually triggered.
}
To differentiate between keyboard and mouse based focus events
You have to hack it by adding an extra keydown event and understand. You can not differentiate it like you want.
If you want to check wheather < select > is clicked by keyboard or mouse,
you can use mousedown() and keypress() event
$('select').mousedown(function(e){
//your code on mouse select
});
and
$('select').keypress(function(e){
//your code on key select
});
I am programming a jQuery plugin which tracks specific events. I have provided 2 JSFiddle examples for the sanitised code to assist at the end of the question.
I am struggling to fathom why 2 particular events are not firing. The first function tracks when the user triggers the backspace or delete keys within an input or textarea field. The code for this:
// Keydown events
$this.keydown(function (e) {
var keyCode = e.keyCode || e.which;
// Tab key
if (e.keyCode === 9) {
alert('tab key');
} else if (e.keyCode === 8 || e.keyCode === 46) { // Backspace and Delete keys
if ($this.val() !== '') {
alert('Backspace or delete key');
}
}
});
I only wish to track the error-correction keys when a field is not empty. The tab key in the above example works as expected within the conditional statement. The backspace and delete keys do not work when inside the plugin and targeting the element in focus.
The second event not firing is tracking whether a user becomes idle. It is making use of jQuery idle timer plugin to manipulate the element in focus.
// Idle event
$this.focus(function() {
$this.idleTimer(3000).bind('idle.idleTimer', function() {
alert('Gone idle');
});
}).focusout(function() {
$this.idleTimer('destroy');
});
With both of these events I have refactored the code. They were outside of the plugin and targeted $('input, select, textarea') and worked as expected. I have brought them inside the plugin, and set them to $(this) to manipulate elements currently in focus. For most of the functions, this has worked without fault, but these 2 are proving problematic.
The first JSFiddle is with the 2 functions inside the plugin. tab works, whereas the correction keys do not. Strangely, in this example the idle function is firing (it does not in my dev environment). As this is working in the JSFiddle, I accept this may be difficult to resolve. Perhaps suggestions on handling an external plugin within my own to remedy this?
Fiddle 1
The second JSFiddle has taken the backspace and delete key functionality outside of the plugin and targets $('input, select, textarea') and now works.
Fiddle 2
For Fiddle1:
if ($this.val() !== '') {
alert('Backspace or delete key');
}
Look at what $this actually is.
I have the same problem as the user in this question, which is due to this bug in Webkit. However, the workaround provided will not work for my app. Let me re-state the problem so that you don't have to go read another question:
I am trying to select all the text in a textarea when it gets focus. The following jQuery code works in IE/FF/Opera:
$('#out').focus(function(){
$('#out').select();
});
However, in Chrome/Safari the text is selected--very briefly--but then the mouseUp event is fired and the text is deselected. The following workaround is offered in the above links:
$('#out').mouseup(function(e){
e.preventDefault();
});
However, this workaround is no good for me. I want to select all text only when the user gives the textarea focus. He must then be able to select only part of the text if he chooses. Can anyone think of a workaround that still meets this requirement?
How about this?
$('#out').focus(function () {
$('#out').select().mouseup(function (e) {
e.preventDefault();
$(this).unbind("mouseup");
});
});
The accepted answer (and basically every other solution I found so far) does not work with keyboard focus, i. e. pressing tab, at least not in my Chromium 21. I use the following snippet instead:
$('#out').focus(function () {
$(this).select().one('mouseup', function (e) {
$(this).off('keyup');
e.preventDefault();
}).one('keyup', function () {
$(this).select().off('mouseup');
});
});
e.preventDefault() in the keyup or focus handler does not help, so the unselecting after a keyboard focus seems to not happen in their default handlers, but rather somewhere between the focus and keyup events.
As suggested by #BarelyFitz, it might be better to work with namespaced events in order to not accidentally unbind other event handlers. Replace 'keyup' with 'keyup.selectText' and 'mouseup' with 'mouseup.selectText' for that.
Why not simply:
$('#out').focus(function(){
$(this).one('mouseup', function() {
$(this).select();
});
});
Seems to work in all major browsers...
A very slightly different approach would be to separate the focus event from the mouse sequence. This works really nicely for me - no state variables, no leaked handlers, no inadvertent removal of handlers, and it works with click, tab, or programmatic focus. Code and jsFiddle below -
$('#out').focus(function() {
$(this).select();
});
$('#out').on('mousedown.selectOnFocus', function() {
if (!($(this).is(':focus'))) {
$(this).focus();
$(this).one('mouseup.selectOnFocus', function(up) {
up.preventDefault();
});
}
});
https://jsfiddle.net/tpankake/eob9eb26/27/
Make a bool. Set it to true after a focus event and reset it after a mouse up event. During the mouse up, if it's true, you know the user just selected the text field; therefore you know you must prevent the mouse up from happening. Otherwise, you must let it pass.
var textFieldGotFocus = false;
$('#out').focus(function()
{
$('#out').select();
textFieldGotFocus = true;
});
$('#out').mouseup(function(e)
{
if (textFieldGotFocus)
e.preventDefault();
});
$(document).mouseup(function() { textFieldGotFocus = false; });
It's important that you put the mouseup listener that resets the variable on document, since it's not guaranteed that the user will release the mouse button over the text field.
onclick="var self = this;setTimeout(function() {self.select();}, 0);"
Select the text before putting the focus on the input box.
$('#out').select().focus();
digitalfresh's solution is mostly there, but has a bug in that if you manually trigger .focus() using JS (so not using a click), or if you tab to the field, then you get an unwanted mouseup event bound - this causes the first click that should deselect the text to be ignored.
To solve:
var out = $('#out');
var mouseCurrentlyDown = false;
out.focus(function () {
out.select();
if (mouseCurrentlyDown) {
out.one('mouseup', function (e) {
e.preventDefault();
});
}
}).mousedown(function() {
mouseCurrentlyDown = true;
});
$('body').mouseup(function() {
mouseCurrentlyDown = false;
});
Note: The mouseup event should be on body and not the input as we want to account for the user mousedown-ing within the input, moving the mouse out of the input, and then mouseup-ing.
tpankake's answer converted to a reusable jQuery function..
(If you upvote this, please also upvote his answer)
Load the following AFTER loading the jQuery library:
$.fn.focusSelect = function () {
return this.each(function () {
var me = $(this);
me.focus(function () {
$(this).select();
});
me.on('mousedown.selectOnFocus', function () {
var me2 = $(this);
if (me2.is(':focus') === false) {
me2.focus();
me2.one('mouseup.selectOnFocus', function (up) {
up.preventDefault();
});
}
});
});
};
Use it like this:
$(document).ready(function () {
// apply to all inputs on the page:
$('input[type=text]').focusSelect();
// apply only to one input
$('#out').focusSelect();
});