How to select elements added via javascript [duplicate] - javascript

This question already has answers here:
adding jQuery click events to dynamically added content
(4 answers)
Closed 9 years ago.
I have a simple code that check a select change and alert a message. This is working ok but when I insert new .select-payment elements on the page this method is only available to the first one and not the ones created via javascript
$(document).ready(function() {
return $(".select-payment").on("change", function() {
return alert("hello");
});
});
Any idea how to make it work for any element that is added after the page is loaded that has a .select-payment class?

$(document).on("change", ".select-payment", function() {
alert("hello");
});
Also returning from within the change handler hardly makes sense, even less, returning the result of an alert.

You could use event delegation like below,
$(document).on('change', '.select-payment', function () {..
Replace the document with any closeby container that exist in DOM when executing the above line
Event delegation binds the event to the parent element and executes the handler when event.target matches the specified selector.

When targeting dynamically created elements, you need to use .on()'s delegated syntax:
$(document).on("change", ".select-payment", function() {
From the docs:
Event handlers are bound only to the currently selected elements; they
must exist on the page at the time your code makes the call to .on().
To ensure the elements are present and can be selected, perform event
binding inside a document ready handler for elements that are in the
HTML markup on the page. If new HTML is being injected into the page,
select the elements and attach event handlers after the new HTML is
placed into the page.

why are you putting return statement ? You must attach your event handler to the document and not the existing .select-payment.
Try this : $(document).on("change",".select-payment",function(){...});

$(document).on("change", ".select-payment", function () {
alert("hello"); }
);
You can replace document with any closer parent element which will always exist in DOM for better performance. Like
$('#closestId').on("change", ".select-payment", function () {
alert("hello");
}
);
if you use $("document") jQuery will search for a node/tag named as document like and wont find anything as document is actually an object.
But you could use $("body") as body is a node/element of DOM.

Related

Can javaScript work on any newly added DOM elemets from an ajax call [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 8 years ago.
I am not an expert in javaScrit , but i have the following concern. I have the following Script :-
<script type="text/javascript">
$(document).ready(function () {
$("#DCSort").click(function () {
what this indicates is the following :-
1. the script will run when the document finishes loading.
2. when the DCSort DOM element is clicked .
my question is as follow:-
let say that after the document loaded , a new element with DCsort have replaced the old DCSort element , will the original javaScrip fire when the newly added DCSort element has been added using an Ajax call and i use click on it ?
Thanks
Replace this -
$("#DCSort").click(function () {
with this -
$("body")on('click', '#DCSort', function () {
This uses event delegation to account for items added to the DOM after it is originally rendered.
You need event delegation in that case:
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
$(document).on('click','#DCSort',function () {

JQuery .on method not responding [duplicate]

This question already has answers here:
jQuery .on() method doesn't see new elements
(5 answers)
Closed 8 years ago.
I am using Jquery 2.1.0. I have injected some elements to the DOM (containing label) into a div element. I am using the following JavaScript to handle click event on all labels but it is completely dead and not responding. I checked and Jquery is loaded.
$('label').on("click", function () {
var ul = $(this).parent().children("ul:first");
if (ul.is(':visible')) {
ul.css({ "display": "none" });
}
else {
ul.css({ "display": "block" });
}
});
I used developer tools in IE 10 and debugged the code. When I hit F5 it goes to my break point (on first line of my code) but when I click a label nothing happens and no errors.
This will only assign the event handler to label elements which exist initially on the page:
$('label').on("click", function () {
// ...
});
To catch elements which are added later, you need to assign the event handler to a common parent element (which isn't added/removed during the life of the page) and filter the source elements, like this:
$(document).on('click', 'label', function () {
// ...
});
Note that there are two selectors:
document
'label'
The first, which is the target of the event handler, is only evaluated once when the page loads (or when this line of code is evaluated, which is generally when the page loads). This attaches the handler to the document object. Since all events "bubble up" to parent elements, this will catch all click events on the page (unless propagation is explicitly stopped, of course).
The second, which is the "filter" for the .on() method's handler, is evaluated any time an event is caught by this handler. It filters out the elements which originated the click event so that the handler is executed only for those which match the filter.
I've actually recently blogged about this very subject.
You need to use event delegation since your label has been dynamically created element:
Event delegation allows us to attach a single event listener, to a
parent element, that will fire for all children matching a selector,
whether those children exist now or are added in the future.
$('body').on('click','label', function() {
// Your code here
});
Basically, event delegation will helps you to attach click event to newly added label elements in your case
you should use event delegation for that
$(document).on("click","label",function(){
});
Event delegation allows you to attach a single event listener, to a parent element, that will fire for all children matching a selector, whether those children exist now or are added in the future.
From this answer to another question here: https://stackoverflow.com/a/8337382/2407870
It seems that the method doesn't work for some inline elements in Chrome. If your element is inline, try changing the display to block.

Extend javascript function into dynamically loaded file

this is the problem:
I' have a page with some .js files embedded, in this files there are some javascript functions.
Now, if I load some content into my page using jQuery load function, the functions before mentioned not affect the new included elements...
What can I do?
function say_ciao(){
alert('Ciao!!!');
}
$('#home_button').on('click', function(){
say_ciao();
});
$('#load_button').on('click', function(){
$('#loader').load('externalpage.php');
});
http://jsfiddle.net/Ppvpp/
Thanks alot for your answers and sorry for my english!
Use event delegation. If the user clicks an element, it'll 'click' all parent elements of that element too. You can use this behaviour:
Instead of
$('#home_button').on('click', function(){
use:
$('selector for parent of that button').on('click', '#home_button', function() {
...
}
The problem is that on the moment you call your function, it'll bind the handler to all elements it matches at that point. If you add a new element that matches that selector, it won't have the handler attached to it (the moment you attached the handler to the elements has already passed). The trick is to attach the handler to a parent object instead (an object that doesn't get dynamically added), and only execute the function if the clicked element matches the selector string in the second argument of .on(). See the docs.

on() function in jquery not working [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 9 years ago.
I am making dynamic buttons using jQuery. Now I want to use this buttons as any other buttons. Here is my HTML:
<label class='twobuttons'><div id="submit-button" >GO!</div></label>
<div id='result'></div>
And here is my JavaScript:
$(document).ready(function(){
$('#submit-button').click(function(){
$('#result').append("<label><div id='share' class='longbutton'>Share this route</div></label>");
$('#result').append("<label><div id='goback' class='longbutton'>Create another one !</div></label>");
});
$('#share').on("click",function(){
alert('hi');
});
$('#goback').on("click",function(){
alert('hello');
})
});
I'm specifically having trouble with the $('#share').on( part.
I tried the on() function as suggested here. But it is not working. Here is the fiddle of my code. Please correct me if I am wrong somewhere.
That isn't how .on() works, if you are dynamically creating elements, you can't bind an event handler to it, because at the point the code runs (document.ready), the element doesn't exist. So to "get around" that, you bind the event to a parent element (that exists) and then add the actual element you'll be clicking on as a parameter like this:
$('body').on("click", "#share", function(){
alert('hi');
});
$('body').on("click", "#goback",function(){
alert('hello');
})
DEMO
You should setup event delegation on #result instead, because by the time you're trying to setup the click handlers on #share, the element itself has not been added yet.
$('#result').on('click', '#share', function() {
// your code here
});
Try not to bind the event handler to $(document) by default; the closest element that will not get removed is the prime candidate.
Alternatively, only bind the click handlers after you've added the new elements.
Update
You're appending elements with a fixed identifier at every click of your button; note that identifiers should be unique per document, so you should make sure that the action is performed at most once.
The way the .on() method works changes according to how you use it. In your example the .on() method behaves similar to bind and will only work on elements that already exist.
Try this:
$(document).on("click",'#share',function(){
alert('hi');
});
DEMO
It's not enough to use .on(). You have to use event delegation with an element (such as document) that existed before your dynamically-created elements:
$(document).on('click', '#share', function () {
alert('hi');
});
(Based on your fiddle, you can use #result instead of document.)
Fiddle

click() assigned in document.ready in jQuery

Do assignments in document.ready (click(fn) specifically) apply to newly appended elements that match the selector?
If not, how can I assign it to this new elements? Do I have to write the assignment after every append or is there a better way?
You are looking for the live functionality. Per the manual:
Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events.
So if you do this:
$(document).ready(function() {
$('div.test').live('click', function() { alert('yipee!'); });
$('body').append('<div class="test">Click me!</div>');
});
When you click on the div you will get the alert even though it was added after the event was bound.

Categories