JavaScript or Jquery Doesn't Work in Dynamically Generated Content

javascript or jQuery doesn't work in dynamically generated content

For dynamically generated elements you should delegate the events, you can use the on method:

$(function() {
$(document).on('click', '#submitUser', function(e) {
var fname = $("#fname").val();
$("#theresult").text(fname);
e.preventDefault();
});
});

live() method is deprecated.

jQuery not firing on dynamically generated content

The problem you have is you are binding the click event only to the elements that are in the DOM when the page loads. If you instead bind the click event to the document and provide a selector it will also work for elements added after the JavaScript runs.

Here is how I think it should work:

    var collapsedSize = '50px';
$(document).on('click', '.page-press .article-text-wrapper .article-icon-showmore', function(e) {
e.preventDefault();
var $articleTextWrapper = $(this).parents('.article-text-wrapper');
if ($(this).hasClass("showless")) {
$articleTextWrapper.find(".article-text").css('height', collapsedSize);
$(this).text("mehr anzeigen").removeClass("showless");
} else {
$articleTextWrapper.find(".article-text").css('height', $articleTextWrapper[0].scrollHeight);
$(this).text("weniger anzeigen").addClass("showless");
}
});

Without the HTML I can't test this JavaScript, but the concept of binding the click event to the document should work.

Click event doesn't work on dynamically generated elements

The click() binding you're using is called a "direct" binding which will only attach the handler to elements that already exist. It won't get bound to elements created in the future. To do that, you'll have to create a "delegated" binding by using on().

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

Source

Here's what you're looking for:

var counter = 0;
$("button").click(function() { $("h2").append("<p class='test'>click me " + (++counter) + "</p>")});
// With on():
$("h2").on("click", "p.test", function(){ alert($(this).text());});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script><h2></h2><button>generate new element</button>

JQuery doesn't recognize dynamically generated id

The problem is with the colon and the periods; you need to escape them in your selector:

if ($("#PAR1\\.1\\:ED").length ){
alert("exists");
}

It's a common problem in JSF, too, where lots of generated ids have a colon inside. While it's not forbidden to use a colon as an id, it conflicts with the meaning of a pseudo-class in a CSS selector.

jQuery click not working for dynamically created items

Do this:

 $( '#wrapper' ).on( 'click', 'a', function () { ... })

$( 'body' ).on( 'click', '.your_dynamic_elem_css_selector', function () { ... }) # use body as wrapper static elem

where #wrapper is a static element in which you add the dynamic links.

So, you have a wrapper which is hard-coded into the HTML source code:

<div id="wrapper"></div>

and you fill it with dynamic content. The idea is to delegate the events to that wrapper, instead of binding handlers directly on the dynamic elements.


Btw, I recommend Backbone.js - it gives structure to this process:

var YourThing = Backbone.View.extend({

// the static wrapper (the root for event delegation)
el: $( '#wrapper' ),

// event bindings are defined here
events: {
'click a': 'anchorClicked'
},

// your DOM event handlers
anchorClicked: function () {
// handle click event
}

});

new YourThing; // initializing your thing

Event handler not working on dynamic content

You have to add the selector parameter, otherwise the event is directly bound instead of delegated, which only works if the element already exists (so it doesn't work for dynamically loaded content).

See http://api.jquery.com/on/#direct-and-delegated-events

Change your code to

$(document.body).on('click', '.update' ,function(){

The jQuery set receives the event then delegates it to elements matching the selector given as argument. This means that contrary to when using live, the jQuery set elements must exist when you execute the code.

As this answers receives a lot of attention, here are two supplementary advises :

1) When it's possible, try to bind the event listener to the most precise element, to avoid useless event handling.

That is, if you're adding an element of class b to an existing element of id a, then don't use

$(document.body).on('click', '#a .b', function(){

but use

$('#a').on('click', '.b', function(){

2) Be careful, when you add an element with an id, to ensure you're not adding it twice. Not only is it "illegal" in HTML to have two elements with the same id but it breaks a lot of things. For example a selector "#c" would retrieve only one element with this id.

.on() not working for dynamically generated content

Not really sure what the issue it, but I'm guessing it has something to do with loading into the same element as the handler is attached to, so try :

$(document).ready(function() {
$(document).on('click', '.mainNav', function(e) {
e.preventDefault();
console.log('I just clicked : '+e.target.href);
$('body').load(e.target.href);
});
});

Also, you are of course aware that this will replace ALL content on your page, and unless there is a new element with the same class in the loaded content, nothing will happen. I would suggest using a container for loading the content into aswell. And of course, the links has to be to actual files on your server.

Also make sure the files you load does not have another set of <head>, <body> tags etc. as that will mess things up for you, HTML content only!

EDIT:

If .mainNav is a <a href="link_you_are_trying_to_load"></a> type of element, you will have to prevent the default action as well, see updated code.

NEW EDIT:

The problem you are having is pretty obvious, you are using elements like :

<div class="mainNav" href="test.php" id="active">

a div element has no attribute href, so JS will not get that value as it's not a valid attribute for anything other than a <a> element

You can either change your element to an <a> element or change the href attribute to:

<div class="mainNav" data-href="test.php" id="active">

and do:

var href = $(this).data('href');

at least that would be valid HTML!

Also, you seem to have a "container" like element called #site so why don't you do :

$('#site').load(href); //using the data-href as above

change event doesn't work on dynamically generated elements - Jquery

Your fiddle has syntax errors. Since a dropdownlist generates a select, let's use one.

For my answer I used THIS HTML, more on this later: things did not match in your code

<select id="specificationAttribute" name="specificationAttribute">
</select>

Code updated: (see inline comments, some are suggestions, some errors)

$(window).on('load', function() {
$("#specificationCategory").on('change',function() {
var selected = $(this).find(":selected");
// if there is a selection, this should have a length so use that
// old: if (selected.val().trim().length == 0) {
if (!selected.length) { // new
// NO clue what this is and not on the fiddle so commented it out
// ShowMessage('please selecet ...', 'information');
alert("select something a category");// lots of ways to do this
} else {
var categoryId = selected.val();
var url = $('#url').data('loadspecificationattributes');
$.ajax({
url: url,
data: {
categoryId: categoryId,
controlId: 'specificationattribute'
},
type: 'POST',
success: function(data) {
// THIS line id does not match my choice of specificationAttribute so I changed it
$('#specificationAttribute').html(data);
},
error: function(response) {
alert(response.error);
}
});
}
});

// THIS should work with the markup I put as an example
$(document).on('change', '#specificationAttribute', function() {
alert("changed ");
});
});// THIS line was missing parts


Related Topics



Leave a reply



Submit