im sorry but I don't know how to call this code. Hence, the title.
$("#e12").select2({
width: "resolve",
tags: ["Cardiologist", "Anesthesiologist", "Neurologist", "Gynecologist", "Andrologist"]
});
That is the code that is populating my input element. However, I want to add an event handler for that. How can I add this?
$('#e12').keypress(function(event) {
if (event.keyCode == 13) {
event.preventDefault();
}
});
P.S. Please tell me what my first code is called.
Your first code is using select2 plugin and is initializing your input with data, which will be used by that input after on.
And use keydown
$('#e12').on("keydown",function(event) {
if (event.keyCode == 13) {
event.preventDefault();
}
});
They're a little different. In this case, keypress isn't inserting anything into your field.
Related
I need to determine the event that causes the focus of an HTML span tag. The span tag is a glyhpicon from bootstrap v3.
Right now, I have a .focus() event handler attached to the span tag to catch when the focus occurs but I can't figure out how to tell if the focus was caused by a click or a tab.
HTML tag: <span class="glyphicon glyphicon-ok-circle col-xs-6"></span>
Jquery:
$("span").focus(function (e) {
var event = "click" //This "event" var is the event that caused the focus
if(event == "click"){
//do something
}else{
//if not a click event, do something else
}
});
Do I use the eventData(e) parameter to detect this?
So far, I haven't been able to find the property that shows what caused the focus inside the eventData(e) parameter. The "originalEvent" property only returns "focus" and not what caused it.
Edit: The answer in Differentiate between focus event triggered by keyboard/mouse doesn't fulfill my question. That user is trying to find whether a click or keyboard event occurs on a jquery "autocomplete" element. I need to find the event that causes the focus on a span tag... not an input tag. The ".focus()" event of the element occurs before all other events.
Answer: Check my post below.
$('span').on('focus', function(e){
$( 'span' ).mousedown(function() {
alert( "focus using click" );
});
$(window).keyup(function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 9) {
// Using tab
}
});
});
I appreciate everyone's feedback! The answer suggested in the comments helped to partially solve the problem. However, I can't give full credit because it didn't fully answer the question.
The answer suggested in the link was to create a "click" and "keypress" event to update a flag that would be checked on the ".focus()" event to determine the source of how it was triggered. My scenario was more complex. The ".focus()" event occurs before a "click()" event... so the flags wouldn't trigger until after the focus has already occurred and passed. The answer also suggested using a "setTimeout()" to make the focus event wait.. which I found unnecessary in my conclusion.
Conclusion
After some research, it was apparent that a ".mousedown()" event occurs before the ".focus()" event. Using the binded flags listed in the suggested answer above, I created the code below to solve my problem.
$(document).bind('mousedown', function () { isClick = true; }).bind('keypress', function () { isClick = false; });
$("span").focus(function () {
if (isClick) {
//Focused by click event
} else{
//Focused by keyboard event
}
});
I also noticed during research that ".bind()" has been deprecated in Jquery v3.0... so I will be switching my code to read:
$(document).mousedown(function () { isClick = true; }).keypress(function () { isClick = false; });
$("span").focus(function () {
if (isClick) {
//Focused by click event
} else{
//Focused by keyboard event
}
});
Please add any comments/suggestions/optimizations as a comment to my answer! Would love to hear other input.
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 have a page with many text input's. All input's share the same class for many reasons.
Now I am trying to capture a the ESC button when an input is focused and alert if the input has value or not.
Now this logically works only for the first field. After the first field, since all input's share the same class, when I press ESC button it gives you the value of the very first input.
So how can I say that I'm talking for the second, fifth or whatever input I am pressing ESC on.
Here is an example: http://jsfiddle.net/Y5e9W/
The first input works fine, the second input thought; when you press ESC it gives you the values of the first.
You should be able to bind the keyup event to the elements with your class, rather than the document. Then this will refer to the element with focus:
$(".gp").keyup(function(e) {
if(e.which === 27) {
if(this.value.length > 0) {
//Has a value!
}
else {
//Empty!
}
}
});
Here's an updated fiddle. Note that I've used the which property of the event object, which jQuery exposes to deal with browser differences between keyCode and charCode.
Update based on comments
If you do need to handle this at the document level, you can use the has method to narrow down your selection of .gp elements to the one which has focus:
if (gj.has(":focus").val() != 0) { //...
Here's another fiddle.
You could do -
$(".gp").keyup(function (e) {
if ($(this).is(":focus") && (e.keyCode == 27)) {
if ($(this).val() != 0){
alert('full');
$(this).val('');
}else{
alert('empty');}
}
});
Which will only respond to the keyup event of elements with the 'gp' class, you can then use this to access the relevant element.
Demo - http://jsfiddle.net/uqS72/2/
I have an input field with class named "form_inputext1".
I am doing some action when pressing ENTER, using this code:
jQuery(".form_inputext1").keypress(function(event) {
console.log(event.keyCode);
if (event.keyCode == '13' || event.which == '13') {
event.preventDefault();
jQuery("#addMoreOptions").click();
return false;
}
});
This part works fine. One of the things it does is it adds one more input field of class "form_inputext1" as a result of an ajax call.
The problem is this newly added field is not associated with the keypress event I wrote. I assume that's because the jQuery code only attach the event to the existing fields, not to the fields added in the future.
How can I work around this? I want this function to apply to onkeypress even for inputs that are not in the DOM yet.
YOu can use Jquery's live:
jQuery(".form_inputext1").live('keypress', function(event) {
console.log(event.keyCode);
if (event.keyCode == '13' || event.which == '13') {
event.preventDefault();
jQuery("#addMoreOptions").click();
return false;
}
});
Or you can add the keypress event when you create the element, which will give you much better performance:
$('.clicker').click(function() {
$('<div class="clicker" />').text('new').appendTo($(this)).keypress(function(event) {
alert(event.which);
})
})
Example of that
Use .live() or .delegate() instead.
http://api.jquery.com/live/
http://api.jquery.com/delegate/
If you use the jQuery live method to bind an event to a class, it will apply even to elements that are added to the DOM after you call the live method.
Documentation: http://api.jquery.com/live/
From the documentation:
To bind a click handler to the target element using this method:
$('.clickme').live('click', function() {
// Live handler called.
});
And then later add a new element:
$('body').append('Another target');
Then clicks on the new element will also trigger the handler.
Use .live():
$('.form_inputext1').live('keypress', function ( event ) {
});
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');
}
}
});