i mean i want make the 'enter' key go from the current input to the next
i mean the 'tab' key function
how i can make 'enter' key do the 'tab' key function
in javascipt
I agree with both of the comments. The worst thing you can do for a user friendly form is breaking the way forms usually work. Altough, if you really want to do it, you have to use a hander on each input for the enter key (key id is 13) and then focuses the next input using the focus() function. That post might help you: http://www.jguru.com/faq/view.jsp?EID=1140915
Using jQuery:
$(document).ready(function () {
$(":input).keypress(function(event) {
if (event.keyCode === 13 || event.keyCode === 10) // 10 is for mac
event.preventDefault();
$(this).next(":input").focus();
}
})
});
This may work if all of your input types are at the same level (siblings).
Otherwise you may need to cache off the $(":input) array and loop through that manually.
Related
Is there really a way with which i could count the number of times, the enter key is pressed in a webpage. Not within an element say, a text box for an example, but rather the whole webpage. say if i open google.com and type something in the search box and hit enter, so the count is one. as such, another search would give 2 enters pressed.any suggestions or ideas?
You can achieve this by using following approach:
var noOfCounts = 0;
$(document).on('keyup', function(e){
if (e.which == 13){
noOfCounts ++;
}
});
You want a JS event listener
MDN Docs
Specifically keydown.
window.addEventListener('keydown', function(e){
console.log(e.keycode);
});
Then figure out which keycode you need and run your validation and other functions from there.
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.
The onblur event in Javascript is triggered when the element loses focus.
The onkeydown occurs on an element that has the focus when a key is pressed down and occurs periodically until the key is released.
If I want to validate a date field, the onkeydown event concerns 9 and 13 (enter and tab key).
But when I press the enter key, then I receive duplicate alert message.
Of course in this case we have two tests, onblur and onkeydown event.
this is the html code :
<html:text onblur="return onDateChange(this);"
onkeydown="return onDateKeyPress(this);"/>
the onDateChange() method is :
function onDateChange(obj){
//validateField is an externatl javascript method which trigger an alert message if we have errors in date
if(validateField(obj,'date',dateFormat)){
//do instructions
}
}
and finally the onDateKeyPress() method is :
function onDateKeyPress(obj){
if(window.event.keyCode == 9)
{
if(validateField(obj,'date',dateFormat))
{
//do instructions
}
}
if(window.event.keyCode == 13)
{
if(validateField(obj,'date',dateFormat))
{
//do instructions
}
}
}
So, the problem is to have one display alert message.
Any suggestions?
you can do it easily with jquery
$('#text_field_id').bind({
blur: function(event) {
if(validateField(this,'date',dateFormat)){
//do instructions
}
},
keydown: function(event) {
if(event.keyCode == 9)
{
if(validateField(this,'date',dateFormat))
{
//do instructions
}
}
if(event.keyCode == 13)
{
if(validateField(this,'date',dateFormat))
{
//do instructions
}
}
}
});
you dont need to include onclick or onkeydown in your text element. One small question you want to execute same instructions in all cases or different instructions???? if you want to execute same instructions, lot of codes can be removed.
In the solution above; keydownFired is true when blur is fired and the if branch of the code does nothing. so nothing happens.
If the blur has something to do other than showing alert; then the follwoing should work.
input.addEventListener('blur', function (e) {
doSomethingThatshldHappenAlwaysOnBLur();
if (keydownFired) {
keydownFired = false
} else {
showAlert();
}
})
Recently I had a problem with having onkeypress and onblur attached to one element. One of the major problems with onkeypress and onkeyblur is that they by nature will trigger each other :) (Triggered? Get it? That's a joke btw. I am bad at jokes, sorry!)
The solution is simple and stupid. Instead of having an alert when onkeypress happens AND when onblur happens you trigger only onblur. How?
//I gave this thing and id. You should always give your things and id. Ids are cool and I love them.
<html:text id="thisIsMyId"
onblur="return onDateChange(this);"
onkeydown="return onDateKeyPress(this)";
/>
the onDateChange() method will stay pretty much the same:
//This will stay the same, you will see why, soon
function onDateChange(obj){
//ValidateField is an externatl javascript method which trigger an alert message if we have errors in date
//If you might have noticed tha **this validate** function is used 3 times, why?
if(validateField(obj,'date',dateFormat)){
//do instructions and **I assume the alert?**
}
}
Now, we will make onDateKeyPress() a little bit blurry :)
//Here is where we strike
function onDateKeyPress(obj){
//This looks weird but it checks if the keycode actually works in the browswer
var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
//Instead of having 2 ifs just make one if with and the logical operator "or" :)
if(keycode == 13 || keycode == 9){
//I am not sure if oyu need to use this but in the example I had, I had to use
//my validation-function otherwise it would just submit
if(validateField(this,'date',dateFormat)){
//If you have a submit form or something this can help
event.stopPropagation();
//we just trigged the onBlur Handler by "blurring" this thing :)
document.getElementById('thisIsMyId').blur();
}
}
With this we did cut one validation and have to write the logic only once. Only in the onDateChange() function.
If someone can make it even better please comment below. I would like to make the code even shorter.
At the end of the day it still depends on the specific situation. It worked for me but this is not a "fits-all-solution".
I need to have an input textbox in which I can click and the cursor starts blinking but the user cannot change any text inside it.
I tried using "readonly" or "disabled" attributes, but they do not allow the cursor to be inside the textbox. So, I was thinking of a solution to implement in JavaScript on a normal textbox. Is there a plugin that already do this? How do I implement this?
EDIT: Thanks for all the answers, but I wanted to make the textarea/input type text as uneditable but selectable at the same time. Pressing Ctrl + A inside the textbox doesn't work. Is it possible to get the changed value and the old value and compare them and then return false if the values are different, but in all other cases return true so that the Ctrl + A, Shift + end, etc. combinations work?
Something like this:
<textarea onkeydown="javascript:return false;"></textarea>
would do the trick. (jsfiddle)
You can also do that at runtime if you want to:
<textarea class="readonly"></textarea>
with
$(".readonly").keydown(function() false);
The onkeydown callback captures keystroke events and cancels them using return false;.
Depending on what you are trying to do, you may want to prevent other kind of events, since it is still possible to change the contents with the mouse, for instance.
Your callback function can accept or cancel events depending of the kind of keystroke. For example, to enable only ctrl-a and ctrl-c (with jQuery):
function keydown(e) {
if(!e.ctrlKey) return false; // Cancel non ctrl-modified keystrokes
if(e.keyCode == 65) return true;// 65 = 'a'
if(e.keyCode == 67) return true;// 67 = 'c'
return false;
}
$(function(){
$("inputSelector").keydown(function(){ return false; });
});
You cannot rely on disabling a <textarea> as a user input, as it's trivial to remove any sort of HTML or javascript disabling with firebug, or other tools. Remember that forms aren't limited to the fields you give them, anyone can submit any data to a page.
Disabled inputs are not submitted with a form anyway, bearing that in mind my advice would be to not use a textarea and just print it out.
I am displaying a form inside a div tag as a dialog to enter details.
In this form, I want to handle the ESC key using jQuery.
If any input tags have focus, keydown event will trigger. If the focus is on the form but not on any input tags then it will not trigger keydown event.
Here is my code:
$("#NewTicket").keydown(function(e) {
var unicode = e.keyCode ? e.keyCode : e.charCode
if (unicode == 27)
{
if (confirm("Are you sure you want to cancel?"))
return true
else
return false
}
});
Just add an id,class to the form
<form id="form">
....
and now do this :
$("#NewTicket,#form").keydown(function(e)
{
var unicode=e.keyCode? e.keyCode : e.charCode
if(unicode == 27)
{
if (confirm("Are you sure you want to cancel?"))
return true
else
return false
}
)};
This should work
You can't focus on forms. If you wan't to handle keydown on elements that don't get focus (such as divs or forms) you have to bind it to the document.
Turns out that jQuery automatically adds :focus selector which enables you to find the focused element by using $(':focus')
I believe that if you put your form in an element made focusable using tabIndex, like , or this focusable div is the container element inside the form, then you can bind the keyDown to this div instead. It works cross browser as far as I've tested but I've not seen this solution discussed much, so curious as to anyone's comments about this.
I know this is an old question but someone still might be looking for an answer.
Usually, I do capture key down at global level then forward it to a function and handle it there. For your needs, you can get nodeName. (Tested in FF, Chrome)
$(document).keydown((e)=>{//Capture Key
if(["INPUT","TEXTAREA"].indexOf(e.target.nodeName)!==-1){//If input in focus
console.log("INPUT FOCUSED",e.code,e.keyCode);
if(e.keyCode==27 || e.code=="Escape"){//Capture Escape key
console.log('ESC');
}
}
});