onblur doesn't work when i clone input - javascript

I want to change input type text to password. But it doesn't work in ie8. I found a solution; clone and replace input but onblur doesn't work after clone.
The debugger doesn't break OnBlur function. Can somebody show me?
Here is js code :
$(document).ready(function () {
var input = document.getElementById("Password");
var input2 = input.cloneNode(false);
input2.id = 'password1';
input2.type = 'password';
$('#Password').focus(function () {
input.parentNode.replaceChild(input2, input);
input2.focus();
});
$('#password1').blur(function () {
if ($(this).val() == '' || $(this).val() == Passwordtxt) {
document.getElementById("password1").setAttribute("type", "text");
$(this).val(Passwordtxt);
}
});
});

Change
$('#password1').blur(function () {
to
$('body').on('focusout','#password1',function () {
See .on()
The focus and blur events are specified by the W3C to not bubble, but jQuery defines cross-browser focusin and focusout events that do bubble. When focus and blur are used to attach delegated event handlers, jQuery maps the names and delivers them as focusin and focusout respectively. For consistency and clarity, use the bubbling event type names.

use on event delegate
try this
$(document).on('blur','#password1',function () {...
replacing the document with the closest element is preffered

Related

Firing a function with onkeydown event

I made a cookie clicker using javascript and html, and at the moment I have it made so that upon clicking an image, it fires a function which increases your score. I want to make it so that instead of only being able to click the image, you can just click any button on the keyboard to fire the same function. I've only seen code to do this in an input field. I'm not sure if "document.addEventListener("keydown", function())" is what I'm looking for.
Try:
document.onkeydown = function() {
console.log('my code');
};
Edit (or):
document.onkeydown = myFn;
To listen for keypress you can add keydown event on document
document.addEventListener("keydown", callBack, false);
function callBack(e) {
var keyCode = e.keyCode;
console.log(keyCode);
}
Just assign a event handler to your event.
If you want to assign for the whole document, use this:
document.addEventListener("keydown", keyDownTextField, false);
document.getElementById("yourinput").addEventListener("keydown", keyDownTextField, false);
function keyDownTextField(e) {
console.log(e.keyCode);
}
<input id="yourinput" type="text" />
document.addEventListener('keydown', () => {
console.log('a');
});
should work.
However, some browsers don't give document focus, which is required for keydown events.
The classic approach to this (which works more universally) is to create an off-screen <input> element, and give it a blur event to regain focus when it loses it. This will force focus to always stay on that input, then it can receive key events.
const input = document.createElement('input');
input.style.position = 'absolute';
input.style.left = '-100000px';
input.addEventListener('blur', () => input.focus());
input.addEventListener('keydown', () => console.log('key down'));
document.body.appendChild(input);
input.focus();
This code:
- creates a new input element
- positions it absolutely way off the left of the screen (so it's not visible)
- adds a blur event which automatically gets focus back
- adds the keydown event itself

Double event handler and one function. How to prevent executing code twice?

I have one callback function bound to two events (change and focusout). However, I need the focusout to happen only when the element we're interacting with is not a checkbox.
This is the example code:
$(document).on('focusout change', '.selector', function() {
if ($(this).is(':checkbox')) {
// Do stuff and prevent the focusout to trigger. HOW???
}
doStuff(); // Action that applies to both cases, but needs to be limited at one execution only
});
The code above will execute twice:
When the checkbox gets checked/unchecked
When you click outside of the checkbox (lose focus (blur))
I tried using .off, but it ends up killing the focousout handler altogether, which I will need later for other elements which aren't checkboxes.
What would be the way to prevent the focusout handler to trigger for certain elements?
What you want to do is
$(document).on('focusout change', '.selector', function(event) {
event is an event object, which has properties, one of which is type. Checking the type you can now see if your function has been called because of a focusout or a change and run code as appropriate
The best way is to affect both events (or more) to the same function, like this :
A text input for example
<input id="myfield" type="text" />
Now the Javascript
var myfield = document.getElementById('myfield');
myfield.onfocus = myfield.onchange = function(e)
{
//your code
}
Yo can even add an other element
button.onclick = myfield.onkeyup = function(e)
{
//when the client press the enter key
if(e.key && e.key == "Enter")
{
//catch the target
}
//when the client click the button
else if(!e.key || e.target == button)
{
//catch the target
}
//otherwise you can do not care about the target and just execute your function
}
You must only know that you can add many elements and many events
element1.onfocus = element1.onblur = element2.onchange = element3.onchange = function(e){//your code}

jQuery - bind multiple events and exclude other events

I've got a search form that has both <input type="text"> and <select> form elements. Listening in to that form I've got this jQuery...
$('#searchform :input').stop().on('keyup change',function(){
// do some ajax stuff
})
The tricksy bit is the way the script listens for multiple events using .on('keyup change' etc.). This works great but there's a problem...
When the input fields lose focus the script jquery listener is triggered.
Here's a demonstration to explain what I mean https://jsfiddle.net/o2k4jf90/1/
I want to do something like this...
$('#searchform :input').stop().on('keyup change not:blur',function(){
// do some ajax stuff
})
...but clearly that's nonsense. What can I do?
Try substituting input event for change , keyup events
$(document).ready(function () {
$(':input').on('input',function(e) {
$('#report').append('stuff happened<br />');
})
});
jsfiddle https://jsfiddle.net/o2k4jf90/3/
The issue is because the change event fires when an input field loses focus, and when the chosen option of a select is modified. To achieve what you need, you would need to bind the events separately. Try this:
$(document).ready(function () {
$('input').keyup(stuffHappened);
$('select').change(stuffHappened);
})
function stuffHappened() {
$('#report').append('stuff happened<br />');
}
Updated fiddle
You can still use a single event handler if you hook the event to the form, however you would need to check the type and target.tagName of the event to achieve the same logic, which is not pretty at all:
$('form').on('keyup change', function(e) {
if ((e.type == 'change' && e.target.tagName == 'SELECT')
|| (e.type == 'keyup' && e.target.tagName == 'INPUT')) {
$('#report').append('stuff happened<br />');
}
});
For this reason, I would suggest using the former method.

How can I bind to the change event of a textarea in jQuery?

I want to capture if any changes happened to <textarea>. Like typing any characters (deleting,backspace) or mouse click and paste or cut. Is there a jQuery event that can trigger for all those events?
I tried change event, but it triggers the callback only after tabbing out from the component.
Use: I want to enable a button if a <textarea> contains any text.
Try this actually:
$('#textareaID').bind('input propertychange', function() {
$("#yourBtnID").hide();
if(this.value.length){
$("#yourBtnID").show();
}
});
DEMO
That works for any changes you make, typing, cutting, pasting.
bind is deprecated. Use on:
$("#textarea").on('change keyup paste', function() {
// your code here
});
Note: The code above will fire multiple times, once for each matching trigger-type. To handle that, do something like this:
var oldVal = "";
$("#textarea").on("change keyup paste", function() {
var currentVal = $(this).val();
if(currentVal == oldVal) {
return; //check to prevent multiple simultaneous triggers
}
oldVal = currentVal;
//action to be performed on textarea changed
alert("changed!");
});
jsFiddle Demo
Use an input event.
var button = $("#buttonId");
$("#textareaID").on('input',function(e){
if(e.target.value === ''){
// Textarea has no value
button.hide();
} else {
// Textarea has a value
button.show();
}
});
This question needed a more up-to-date answer, with sources. This is what actually works (though you don't have to take my word for it):
// Storing this jQuery object outside of the event callback
// prevents jQuery from having to search the DOM for it again
// every time an event is fired.
var $myButton = $("#buttonID")
// input :: for all modern browsers [1]
// selectionchange :: for IE9 [2]
// propertychange :: for <IE9 [3]
$('#textareaID').on('input selectionchange propertychange', function() {
// This is the correct way to enable/disabled a button in jQuery [4]
$myButton.prop('disabled', this.value.length === 0)
}
1: https://developer.mozilla.org/en-US/docs/Web/Events/input#Browser_compatibility
2: oninput in IE9 doesn't fire when we hit BACKSPACE / DEL / do CUT
3: https://msdn.microsoft.com/en-us/library/ms536956(v=vs.85).aspx
4: http://api.jquery.com/prop/#prop-propertyName-function
BUT, for a more global solution that you can use throughout your project, I recommend using the textchange jQuery plugin to gain a new, cross-browser compatible textchange event. It was developed by the same person who implemented the equivalent onChange event for Facebook's ReactJS, which they use for nearly their entire website. And I think it's safe to say, if it's a robust enough solution for Facebook, it's probably robust enough for you. :-)
UPDATE: If you happen to need features like drag and drop support in Internet Explorer, you may instead want to check out pandell's more recently updated fork of jquery-splendid-textchange.
2018, without JQUERY
The question is with JQuery, it's just FYI.
JS
let textareaID = document.getElementById('textareaID');
let yourBtnID = document.getElementById('yourBtnID');
textareaID.addEventListener('input', function() {
yourBtnID.style.display = 'none';
if (textareaID.value.length) {
yourBtnID.style.display = 'inline-block';
}
});
HTML
<textarea id="textareaID"></textarea>
<button id="yourBtnID" style="display: none;">click me</div>
Here's another (modern) but slightly different version than the ones mentioned before. Tested with IE9:
$('#textareaID').on('input change keyup', function () {
if (this.value.length) {
// textarea has content
} else {
// textarea is empty
}
});
For outdated browsers you might also add selectionchange and propertychange (as mentioned in other answers). But selectionchange didn't work for me in IE9. That's why I added keyup.
try this ...
$("#txtAreaID").bind("keyup", function(event, ui) {
// Write your code here
});
Try to do it with focusout
$("textarea").focusout(function() {
alert('textarea focusout');
});
.delegate is the only one that is working to me with jQuery JavaScript Library v2.1.1
$(document).delegate('#textareaID','change', function() {
console.log("change!");
});
After some experimentation I came up with this implementation:
$('.detect-change')
.on('change cut paste', function(e) {
console.log("Change detected.");
contentModified = true;
})
.keypress(function(e) {
if (e.which !== 0 && e.altKey == false && e.ctrlKey == false && e.metaKey == false) {
console.log("Change detected.");
contentModified = true;
}
});
Handles changes to any kind of input and select as well as textareas ignoring arrow keys and things like ctrl, cmd, function keys, etc.
Note: I've only tried this in FF since it's for a FF add-on.
Try this
$('textarea').trigger('change');
$("textarea").bind('cut paste', function(e) { });

Jquery Listbox Change event does not fire on Keyboard scrolling

I've got a simple Listbox on a HTML form and this very basic jQuery code
//Toggle visibility of selected item
$("#selCategory").change(function() {
$(".prashQs").addClass("hide");
var cat = $("#selCategory :selected").attr("id");
cat = cat.substr(1);
$("#d" + cat).removeClass("hide");
});
The change event fires fine when the current item is selected using the Mouse, but when I scroll through the items using the keyboard the event is not fired and my code never executes.
Is there a reason for this behavior? And what's the workaround?
The onchange event isn't generally fired until the element loses focus. You'll also want to use onkeypress. Maybe something like:
var changeHandler = function() {
$(".prashQs").addClass("hide");
var cat = $("#selCategory :selected").attr("id");
cat = cat.substr(1);
$("#d" + cat).removeClass("hide");
}
$("#selCategory").change(changeHandler).keypress(changeHandler);
You'll want both onchange and onkeypress to account for both mouse and keyboard interaction respectively.
Sometimes the change behavior can differ per browser, as a workaround you could do something like this:
//Toggle visibility of selected item
$("#selCategory").change(function() {
$(".prashQs").addClass("hide");
var cat = $("#selCategory :selected").attr("id");
cat = cat.substr(1);
$("#d" + cat).removeClass("hide");
}).keypress(function() { $(this).change(); });
You can chain whatever events you want and manually fire the change event.
IE:
var changeMethod = function() { $(this).change(); };
....keypress(changeMethod).click(changeMethod).xxx(changeMethod);
The behavior you describe, the change event triggering by keyboard scrolling in a select element, is actually an Internet Explorer bug. The DOM Level 2 Event specification defines the change event as this:
The change event occurs when a control
loses the input focus and its value
has been modified since gaining focus.
This event is valid for INPUT, SELECT,
and TEXTAREA. element.
If you really want this behavior, I think you should look at keyboard events.
$("#selCategory").keypress(function (e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 38 || keyCode == 40) { // if up or down key is pressed
$(this).change(); // trigger the change event
}
});
Check a example here...
I had this problem with IE under JQuery 1.4.1 - change events on combo boxes were not firing if the keyboard was used to make the change.
Seems to have been fixed in JQuery 1.4.2.
$('#item').live('change keypress', function() { /* code */ });

Categories

Resources