bind .keyup to dynamically created element - javascript

I have seen a bunch of questions on this but im still stumped. I could realy use some help understanding what im doing wrong here.
(my terminology may not be correct below)
I have a textarea and a .keyup function bound to it by class name
This first textarea fires the function fine
I then add a second textarea dynamically which is intended to fire the same function
My .keyup function
$('.trans').keyup(function() {
alert("Working");
});
I understand that the above doesnt work on the newly created textarea because it wasnt part of the DOM when the function was bound. I have tried several ansers to other questions but cant seem to get this working:
Other things Ive tried:
// I also tried this
// Neither textarea responds if this is used
$('.trans').on('keyup', '.newTrans', function() {
alert("Working");
});
// I also tried this
// Only the first textarea responds
$('.trans').delegate('.newTrans', 'keyup', function(){
alert("Working");
});
Here is a JSfiddle with more of the code im using if needed:
jSfiddle

The .on() method isn't going to work in your fiddle at all because you have specified an old version of jQuery from before .on() was introduced.
If you upgrade to a newer version of jQuery (at least 1.7) you can do this:
$(document).on('keyup', '.trans', function() {
alert("Working");
});
Demo: http://jsfiddle.net/VFt6X/4/
If you need to keep using v1.6.4 for some reason then use the .delegate() method instead:
$(document).delegate('.trans', 'keyup', function() {
alert("Working");
});
Demo: http://jsfiddle.net/VFt6X/5/
Note that either way the '.trans' selector for the elements you care about is passed as a parameter to the function. The $(...) part on the left has to specify some container that already exists. I've used document, but it is better to specify something closer to the elements in question if possible, so in your case you could use $("#centerNotes").

Try this:
$('.trans').live('keyup', function() {
alert("Working");
});
http://jsfiddle.net/VFt6X/3/

Related

Can't seem to get JQuery's .on() working for elements created through scripting

I have a system that generates multiple address fields according the an amount selected by the user.
Initially I used $("input[name=inputname]") which works fine for the initially loaded fiedls but doesn't work when adding more. Searching google and here led me to believe I could use JQuery's .on function, although I can't seem to get it working, is there anything wrong with this code or do I need to approach this a different way?
$("div.data").on( "change", "input[name^=delivery-address-1]", function() {
alert( $( this ).val() );
});
Thanks in advance
EDIT: Hi, regarding the 'marked as duplicate', as I said I have read the similar answers and am aware of them, but the code learned from these answers doesn't seem to work in my situation and so was looking for further help, thanks.
Try using document and not 'div.data' like so:
$(document).on("change", "input[name^=delivery-address-1]", function() {
alert($(this).val());
});
From my experience (and not just mine), it's often better to handle events of dynamic elements at global level. Meaning you will attach the event handler to document and use the selector filter to fire it only for matching elements.
eg:
$(document).on('change', 'input[name^=delivery-address-1]', function(){
alert('hello');
});

jQuery .click() and alert() issues

I am new to jQuery and am having a few issues. This jsFiddle shows what I am experiencing: http://jsfiddle.net/rE2FH/5/ Note how the button does nothing.
What I am trying to do is set a click listener to the button and have it do an alert();. However, the neither the click event or the alert() is working.
I have tried the click event as .click(), .on(), .delegate(), and .live() none of which seem to work. As for the alert, I cannot find anything other than the equivalent to "It automagically works if you do 'alert([sting]);'!" I am aware the .click() is for 1.7+, .live() is depreciated and even then .delegate() is preferred over it.
In my current project I am using jsp with the script
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> HOWEVER, it does not work in the jsFiddle either. This version works fine on some of our other pages (alert and .click events), but for some reason the one I'm currently working on has issues. I have done everything I can see to emulate those other pages as well, but I may be missing something. The guy who wrote that jQuery is no longer with our company.
I have already searched SO, and none of these results have worked for me:
jQuery .click() not functioning
jQuery .click() problem
jquery button not respond to click method
jquery click event issues
+others that are all along the same lines.
Any insight would be appreciated.
You had several issues. Make sure you check the javascript console for errors. Here's a working version:
http://jsfiddle.net/LxuVy/
$(document).ready(function(){
$(document).delegate('#but', 'click', buttonClick);
function buttonClick() {
$('#res').hide().html("BUTTON!!!").fadeIn('fast');
alert("Hello!");
}
});
To break down the issues with yours:
$(document).ready(function(){
$.delegate('#but', 'click', buttonClick());
function buttonClick(){
$('#res').hide().html("BUTTON!!!").fadeIn('fast');
alert("Hello!");
}; // this semi-colon shouldn't be here
}; // missing closing paren for ready()
delegate is used like this:
$('selector').delegate(...)
Though delegate() has been replaced by on(), which should be used instead.
Also, buttonClick() should be buttonClick. When you add the parentheses, you are executing the function. What you want to do in this case is pass the function as a parameter.
You are missing the closing ) from the document.ready:
$(document).ready(function(){
$.delegate('#but', 'click', buttonClick());
function buttonClick(){
$('#res').hide().html("BUTTON!!!").fadeIn('fast');
alert("Hello!");
};
});
I would also suggest using .on() like this: http://jsfiddle.net/rE2FH/23/
Multiple probleme.
First you need to select an element with delegated (closest static parent)
$(document).delegate(...)
The function in the parameter should not finish with braket
$(document).delegate('#but', 'click', buttonClick);
And you are missing a closing parenthesis.
Fiddle : http://jsfiddle.net/rE2FH/18/
But since your button is static, you can use click directly :
$('#but').click(buttonClick);
Also, delegated is deprecated, you should use .on().
I see three problems:
.delegate is also deprecated, you should be using .on. You are also calling it wrong, directly on $. Finally, you're not actually delegating the event to any ancestor, so you could very well be using .click directly.
Instead of passing a function reference when binding the event, you're calling the function (you're passing buttonClick() instead of buttonClick).
You forgot to close a parentheses at the end, causing a syntax error (always check you browser's console, it will show this kind of error).
Fixing all that, your code would be:
$(document).ready(function(){
// using .click instead of .delegate
// .on('click', buttonClick) would work too
$('#but').click( buttonClick );
// no calling parentheses -^
function buttonClick(){
$('#res').hide().html("BUTTON!!!").fadeIn('fast');
alert("Hello!");
}
});
// added missing ) at the end

jquery on() change on textbox not working using jQ 1.8.3

I am using jquery 1.8.3 so trying to change from using .live() to the .on()
Like many others on SO - cant get it worrking - what am i doing wrong? If its so wrong to use .live()
why does it work so consistently well!
( txtbxhost is a textbox NOT added dynamically its already in the DOM )
$('#txtbxhost').live('input', function() {
// works everytime
});
$('#txtbxhost').on('change', 'input', function() {
// fails everytime
});
and
$('#txtbxhost').on('change', '#txtbxhost', function() {
// fails everytime
});
and
$(document).on('change', '#txtbxhost', function() {
// fails everytime
});
i'm out of ideas here ... help ...
You probably want:
$(document).on('input', '#txtbxhost', function() {
// code here
});
Check this fiddle
Also, change works only when you blur - In other words click elsewhere after you change text in the texbox.
So, this should work too
$(document).on('change', '#txtbxhost', function() {
// fails everytime
});
Check the updated fiddle
You need to understand how on() differs in behavior to live().
There are really two main approaches to using on(). If the element you are interested in exists on the page at load, you can consider directly binding the event like this:
$('#txtbxhost').on('input', function () {
// some function
});
This would work in much the same way as change() would.
If the element may not exist at page load then you need to work with delegated events. To do this, you must attach the on() to an element that does exist at page load. This can be document or would typically be the closest ancestor to the element the you are interested in that exists on page load. This delegation works by looking at the event bubbling up the DOM element stack to the element to which you bind on(), you then look for a selector within that element to apply the callback to. This looks like this:
$('#some_static_ancestor').on('input', '#txtbxhost', function () {
// some function
});
$(function(){
$('#txtbxhost').on('input', function() {
// do stuff
});
});
That should do it.
In your case you don't really need to use .on(), it's main purpose is to deal with dynamically created elements.

confused with jquery after() behavior

Following is a piece of jquery code that is driving me nuts
var count = 0;
$('#some-element-id').click(function(){
var currentElement = '#new-div-id-'+count;
$(currentElement).after($('<div id="new-div-id-'+(++count)+'">Hello World!<span class="delete_me">x</span></div>'));
});
$(".delete_me").click(function () {
alert('Deleting!');
});
Now accordingly when I click on element with id some-element-id a new div is inserted and I see the x character. But clicking x doesn't do any thing. No error. As per http://api.jquery.com/after I can insert elements this way which is working fine. I can ee the new elements in DOM tree using Firebug. Now why no event is fired when I click on span? For some unknown reason I am forced to use jQuery 1.3.2 but that should not be a problem.
Update 1
I understand that I am trying to bind an even to an element that doesn't exist in the DOM. But please note that even is not fired, the event will be fired after the element is embedded in the DOM. I used following code and even it doesn't work
$("span.delete_me").live('click',function () {
alert('Deleting!');
});
There is no error on the console.
Update 2
Here is the actual rendered code http://jsfiddle.net/8sjcZ/
See http://jsfiddle.net/vKwm6/
Use the live method:
$(".delete_me").live("click", function () {
alert('Deleting!');
});
At the time you call the .click method in your post, the "x" doesn't exist.
try
$(".delete_me").live('click',function () {
alert('Deleting!');
});
your .click() is not working because the .delete_me class is not in DOM at time you call .click() so binding never takes place. .live() ensures that binding takes place for elements which are created at runtime.
hmmm you need to do it with live()
$(".delete_me").live('click',function () {
alert('Deleting!');
});
live() will apply to dynamically added objects
http://api.jquery.com/live/

With jQuery, how can I use the "live" method to alert when a new element is added?

First off, I don't want another plugin to do this... jQuery already has the functionality to do 99% of what I want with the live() method.
Basically, I want to change this:
$(".some-button").live("click", function() { alert('yay!'); });
into this:
$(".some-button").live(function() { alert('yay!'); });
So, what I'm saying is that I want to fire a method right away when an element is added to the page... jQuery can already do this SOOO close because that's how it adds the "click" even in my example above!
How can I achieve this without adding another plugin, but rather, just by using the same functionality as the "live" and "die" methods do?
Here's some code I've copied and pasted that seems to work in fiddle, at least on FF: http://jsfiddle.net/KQBzn/
$(document).bind('DOMNodeInserted', function(event) {
alert('inserted ' + event.target.nodeName + // new node
' in ' + event.relatedNode.nodeName); // parent
});
source: http://forum.jquery.com/topic/how-to-get-notified-when-new-dom-elements-are-added
There isn't any cross-browser way to do this, and there's nothing in jQuery itself that allows it.
You'd have to use a plugin, or just manage invoking code for your new elements manually.
The the live()[docs] method and the delegate()[docs] method are only for event handling. The code you give them will only respond to browser events, not to DOM manipulation.
The reason .live() won't do this is because it does not run any code when adding new elements to the DOM. It isn't monitoring any DOM changes. Rather it is responding to events that bubble to the document, and invoking the handler if it matches the selector you gave it.
You can't do it with the .live() method.
It seems jQuery should add a feature to the .live() method so that if its used with a specific keyword like 'created' instead of an event name then it will let you execute a function for the created element. That'd be cool! For example, the ideal scenario would be like this:
$('.foobar').live('created', function() {
// do something with each newly created .foobar element here.
});

Categories

Resources