Why doesn't jQuery function properly on keydown? - javascript

I have this external jQuery code:
jQuery(document).one('keydown', 'g',function (evt){
if ($("#tb").html() == "0")
{
$("#tb").html("Testing the chicken.")
} else {$("#tb").html("Chickens fart too.")}
return false;});
There are no errors in console.
I know it's rather silly, but never mind the text in .html(). Anyways, whenever I go to the webpage it just replaces the default 0 in the page with nothing. Then, when I press any key nothing happens. Ultimately, what I want this script to do in the end is display the letter or number that the user types in the tb div.
P.S. I'm new to stackoverflow so please tell me if my formatting is wrong or if I broke a rule.
Okay, so I edited the code and here is what I have:
$('#tb').on("keydown", function(event) {
if ($("#tb").html() == "0")
{
$("#tb").html("Testing the chicken.")
} else {$("#tb").html("Chickens fart too.")}
});
It still doesn't work.

A div element does not have a keydown event. Only element that have focus property can have it.
So I think you are referring to a input inside the div..
HTML
<div id="tb">
<span class="output"></span>
<input type="text" />
</div>
JS
// Delegating the event on input to it's container
$('#tb').on("keydown", 'input', function (event) {
// $(this).val() - Gets the value of the input on keydown
if ($(this).val() === "") {
// Set the html for span inside div
$(".output").html("Testing the chicken.");
} else {
$(".output").html("Chickens fart too.");
}
});
Check Fiddle
// Bind event to the document which fires when document is focussed and
// a key is pressed
$(document).on('keydown', function(event) {
// Key code for g
if(event.keyCode === 71) {
// Bind the event to the input when g is pressed
$('#tb input').on('keyup', inputKeydown);
// unbind the event on document as no longet necessary
$(document).off('keydown');
}
return;
});
function inputKeydown() {
// $(this).val() - Gets the value of the input on keydown
if ($(this).val() === "") {
// Set the html for span inside div
$(".output").html("Testing the chicken.");
} else {
$(".output").html("Chickens fart too.");
}
}
Another Fiddle

Related

How to reference all <input> and <textarea> and do an action if they have :focus?

I am trying to use plain Javascript to set up a function that fires when the S key is pressed AND the search overlay is not already open AND the S is not pressed when inside an <input> or <textarea>. The issue is in the third argument and I can't seem to figure it out.
Can you please tell me how to set up the third argument in the IF statement?
I have been trying to get an equivent of the JQuery is() function in regular JS. Since I don't know much about JS I am avoiding JQuery until I get the basics down. I have created a class for OOP, so the this. is referencing that.
My Javascript:
keyPressControl(event) {
if (event.keyCode == 83 && !this.isOverlayOpen && !document.querySelectorAll('input, textarea').hasFocus()) {
this.staffSearchOpen();
}
}
The this.staffSearchOpen(); should function when all three arguments noted above are true, but I can only get the first two to work properly.
The wording of the question is a little confusing but it looks like you're trying to exclude event that happen when an input field is in focus, not the other way around.
Instead of "hasFocus()" you could just build the rule into the selector itself as input:focus, textarea:focus:
document.addEventListener('keypress', function() {
if (document.querySelector('input:focus, textarea:focus')) {
console.log("keypress event was inside an input")
} else {
console.log("No input in focus");
}
})
<input>
<textarea></textarea>
...so your function could be:
keyPressControl(event) {
if (
event.keyCode == 83 &&
!this.isOverlayOpen &&
!document.querySelector('input:focus, textarea:focus')
) {
this.staffSearchOpen();
}
}
Do it the other way around:
var elems = document.querySelectorAll('input, textarea');
elems.foreach(function (elem) {
this.addEventListener("keydown",keyPressControl);
});
keyPressControl(event) {
//you won't get a key event here unless the element is the focus owner
if (event.keyCode == ...) {
this.staffSearchOpen();
}
}

jquery - add event handler on event that takes another event as argument

I am trying to call a function scheduleAdd when the enter button is hit, but I only want it to work if an input with the id 'addSchedule' is in focus. Here's what I have:
$('#addSchedule').focus(function(e) {
var evt = e || window.event;
if(evt.keyCode == 13) {scheduleAdd};
});
I know the code inside the .focus works, because I tried it on its own and it triggers the function scheduleAdd when the enter key is hit. How can I make this conditional on 'addSchedule' being in focus?
Also, more generally, I was wondering if there's a standard way to ascribe event handlers conditional on a second event, such as nesting .on() or something.
Thanks.
Demo on fiddle
HTML:
<form>
<input id="addSchedule" type="text" />
</form>
Javascript:
$('#addSchedule').keydown(function (event) {
if (event.which == 13) {
event.preventDefault(); // This will prevent the page refresh.
scheduleAdd();
}
function scheduleAdd() {
alert("Add the schedule");
}
});
Simply the keydown event, and decide to do something or nothing based on whether the current element has the specified id:
$(document).on("keydown", function() {
if (!$("#addSchedule").is(":focus")) return;
// do stuff
});
Alternatively you can also check for the identity of the focused element with document.activeElement.id === "addSchedule" if you don't mind that's not enough jQuery. ;-)

javascript onChange computation - show only one alert

I didnt know how to properly name my question, but here goes.
In my html i have a "form" but not
<form></form>
.It is just a couple of selects, radio buttons and text inputs.
I enter, check and select values and according to these values, some computation is done. This "form" is computing on every keydown, blur, change. So when I change one value it will immediately recalculate the results with new value.
I would like to alert the user, when he didnt fill any of the necessary inputs. Here is how it works now (this is in a separate .js file)
function calculator() {
// Here is code that gathers the data from html
// and here are also some computations (many if-s)
// The code is too long to be putted here
}
$(function () {
$('select, input').on('keydown blur change', calculator);
});
I tried to put a if statement inside of my calculator function:
function calculator() {
// Here is code that gathers the data from html
// and here are also some computations (many if-s)
// The code is too long to be putted here
if (val1 == '' && sadzba == '' && viem == '' && ...) {
alert('You have to fill all necessary fields!')
}
}
This obviously caused, that the alert was popped every time I enter / choose new value, because at the beginning all variables are empty / with no value.
So how can I achieve, this situation: User fills in the "form" except of (for example)one value and only then will the alert pop up.
Than you.
I suggest to do the check on submit and return false if one of the fields is empty, preventing the form to be submitted.
$('form').on('submit', function () {
if (val1 == '' || sadzba == '' || viem == '') {
alert('You have to fill all necessary fields!');
return false;
} else { return true; }
});
Use a different event handler for the onblur event since that's when the cursor has left the input box. (It also prevents the event handler from firing all the time. That's a pretty expensive process and it can slow your page down)
$('select, input').on('blur', didTheyLeaveTheFieldEmpty);
Hope I understood you right, you can try this:
function calculator(event) {
if ( $(event.target).val().length == 0 ) {
alert('fill the field');
}
}
$('select, input').on('keyup', calculator);
even if you don't want a form with a submit buton you can create a button
and trigger your code on it's click
<input type="button" class="calculate">
$(function () {
$('.calculate').on('click', calculator);
});

jQuery: fire keyup on all document excluding one input text field

I have a
$(document).keyup(function(e) {
//some code is here
});
code, that works as expected: it fires when I press any key on the keyboard.
I want it to fire, but not when the cursor is in the
<input type="text" id="excludeMeFromFiring">
which is on the page.
How to modify the code above to exclude firing when typing in the input text field with a special id? So it doesn't fire if the cursor is in the input text field.
Thank you.
It's easy to do that in the keyup function:
$(document).keyup(function(e) {
if ($(e.target).closest("#excludeMeFromFiring")[0]) {
return;
}
// It's not that element, handle it
});
That's the general case; because input elements can't have any elements within them, you could just use e.target.id rather than closest:
$(document).keyup(function(e) {
if (e.target.id === "excludeMeFromFiring") {
return;
}
// It's not that element, handle it
});
I use closest whenever the element can have other elements inside it.
Try
$(document).keyup(function (e) {
if(e.target.id === 'excludeMeFromFiring'){
console.log('no');
}else{
console.log('hi');
}
});
$(document).keyup(function (e) {
if(e.target.id !== 'excludeMeFromFiring'){
console.log('hi');
}
});
Another Example:
$('#excludeMeFromFiring').keyup(function(e) {
e.stopPropagation();
});

Global click event blocks element's click event

This should happen
If the user clicks on one of the two input boxes, the default value should be removed. When the user clicks elswhere on the webpage and one text field is empty, it should be filled with the default value from the data-default attribute of the spefic element.
This happens
When somebody clicks somewhere on the page and the field is empty, the field will be filled with the right value, but when somebody clicks in the field again the text isn't removed. It seems like the $(document) click event is blocking the $(".login-input") click event, because the $(".login-input") is working without the $(document) click event.
JSFiddle
A sample of my problem is provieded here: JSFiddle
Tank you for helping!
When you click on the input, the script is working, but since the input is in the document, a click on the input is a click on the document aswell. Both function will rune, document is the last one.
That is called event bubblingand you need to stop propagation :
$(document).ready(function () {
$(".login-input").click(function (e) {
e.stopPropagation()
$(this).val("");
});
});
Fiddle : http://jsfiddle.net/kLQW9/3/
That's not at all how you solve placeholders, you do it like so :
$(document).ready(function () {
$(".login-input").on({
focus: function () {
if (this.value == $(this).data('default')) this.value = '';
},
blur: function() {
if (this.value == '') this.value = $(this).data('default');
}
});
});
FIDDLE
Preferably you'd use the HTML5 placeholder attribute if really old browsers aren't an issue.
EDIT:
if you decide to do both, check support for placeholders in the browser before applying the javascript :
var i = document.createElement('input'),
hasPlaceholders = 'placeholder' in i;
if (!hasPlaceholders) {
// place the code above here, the condition will
// fail if placeholders aren't supported
}
Try below code
$(document).ready(function () {
$(".login-input").click(function () {
$(this).val("");
});
});
$(document).ready(function () {
$(".login-input").each(function () {
if ($(this).val() === "") {
$(this).val($(this).attr("data-default"));
}
});
$(".login-input").blur(function () {
if ($(this).val() === "") {
$(this).val($(this).attr("data-default"));
}
});
});
Check fiddle
Why not to use focus and blur events?
$(document).ready(function () {
$(".login-input").focus(function () {
$(this).val("");
});
});
$(document).ready(function () {
$(".login-input").blur(function () {
if ($(this).val() === "") {
$(this).val($(this).attr("data-default"));
}
});
});
http://jsfiddle.net/kLQW9/5/
P.S. In yours, and this code, on focus all data fro input will be cleared. If you need to clear only default text, add proper condition for that.

Categories

Resources