How to work with dynamically created fields? - javascript

I have web layout, which can contains several links on it. Those links are dynamically created, using AJAX functions. And it works ok.
But, I don't know how can I work with those "dynamically created links" (ie. how to call some JS or jQuery function if I click on them). I guess that browser can not recognize them, since there are created after page is loaded.
Is there some function, that can "re-render" my page and elements on it?
Tnx in adv on your help!

You can use the 2 following methods jQuery provides:
The first one, is the .live() method, and the other is the .delegate() method.
The usage of the first one is very simple:
$(document).ready(function() {
$("#dynamicElement").live("click", function() {
//do something
});
}
As you can see, the first argument is the event you want to bind, and the second is a function which handles the event. The way this works is not exactly like a "re-rendering". The common way to do this ( $("#dynamicElement").click(...) or $("#dynamicElement").bind("click", ...) ) works by attaching the event handler of a determinate event to the DOM Element when the DOM has properly loaded ($(document).ready(...) ). Now, obviously, this won't work with dynamically generated elements, because they're not present when the DOM first loads.
The way .live() works is, instead of attaching the vent handler to the DOM Element itself, it attaches it with the document element, taking advantage of the bubbling-up property of JS & DOM (When you click the dynamically generated element and no event handler is attached, it keeps looking to the top until it finds one).
Sounds pretty neat, right? But there's a little technical issue with this method, as I said, it attaches the event handler to the top of the DOM, so when you click the element, your browser has to transverse all over the DOM tree, until it finds the proper event handler. Process which is very inefficient, by the way. And here's where appears the .delegate() method.
Let's assume the following HTML estructure:
<html>
<head>
...
</head>
<body>
<div id="links-container">
<!-- Here's where the dynamically generated content will be -->
</div>
</body>
</html>
So, with the .delegate() method, instead of binding the event handler to the top of the DOM, you just could attach it to a parent DOM Element. A DOM Element you're sure it's going to be somewhere up of the dynamically generated content in the DOM Tree. The closer to them, the better this will work. So, this should do the magic:
$(document).ready(function() {
$("#links-container").delegate("#dynamicElement", "click", function() {
//do something
});
}
This was kind of a long answer, but I like to explain the theory behind it haha.
EDIT: You should correct your markup, it's invalid because: 1) The anchors does not allow the use of a value attribute, and 2) You can't have 2 or more tags with the same ID. Try this:
<a class="removeLineItem" id="delete-1">Delete</a>
<a class="removeLineItem" id="delete-2">Delete</a>
<a class="removeLineItem" id="delete-3">Delete</a>
And to determine which one of the anchors was clicked
$(document).ready(function() {
$("#links-container").delegate(".removeLineItem", "click", function() {
var anchorClicked = $(this).attr("id"),
valueClicked = anchorClicked.split("-")[1];
});
}
With that code, you will have stored in the anchorClicked variable the id of the link clicked, and in the valueClicked the number associated to the anchor.

In your page initialization code, you can set up handlers like this:
$(function() {
$('#myForm input.needsHandler').live('click', function(ev) {
// .. handle the click event
});
});
You just need to be able to identify the input elements by class or something.

How are these links dynamically created? You can use use the correct selector, given that they are using the same class name or resides in the same tag, etc.

consider the html form
<form>
<input type="text" id="id" name="id"/>
<input type="button" id="check" name="check value="check"/>
</form>
jquery script
$('#check).click(function() {
if($('#id).val() == '') {
alert('load the data!!!!);
}
});
here on clicking the button the script check the value of the textbox id to be null. if its null it will return an alert message....
i thin this is the solution you are looking for.....
have a nice day..

Noramlly , the browser process response HTML and add it to DOM tree , but sometimes , current defined events just not work , simply reinitialize the event when u call the ajax request ..

All you need to do to work with dynamically created elements is create identifiers you can locate them with. Try the following code in console of Firebug or the developer tools for Chrome or IE.
$(".everyonelovesstackoverflow").html('<a id="l1" href="http://www.google.com">google</a> <a id="l2" href="http://www.yahoo.com">yahoo</a>');
$("#l1").click(function(){alert("google");});
$("#l2").click(function(){alert("yahoo");});
You should now have two links where the ad normally is that were dynamically created, and than had an onclick handler added to bring up an alert (I didn't block default behaviour, so it will cause you to leave the page.)
jQuery's .live will allow you to automatically add handlers to newly created element.

If your links are coming in via AJAX, you can set the onclick attributes on the server. Just output the links into the AJAX like this:
Holy crap I'm a link
The return false makes sure the link doesn't reload the page.
Hope this helps!

Related

jQuery: last doesn't work with mixed tags

I am having html look like below:
<td id="sample">
<select>
<option>
</select>
<br/>
<select>
<option>
</select>
<br/>
//...
</td>
I know we should be using div instead of table but our whole webpage is designed this way and it is kind of time-consuming to change it.
What I am trying to do is add a event handler to the change of last select tag. I have tried:
$("#sample > select:last") and $("#sample").find("select).last() but both of them tend to find the last select before br tag which means the first one. I can probably solve this issue with adding an attribute in my code but that will result in adding a global variable and an amount of code. Is there a cleaner solution?
Edit:
Sorry that I didn't understand my issue correctly and many thanks to all the comments. I guess my issue actually is I put the event handler in my document ready section and append more <select> in that event handler. So every time when I am trying to trigger the event, it always come to the original last element.
My code looks like:
$('#sample > select:last').on('change', function() {
$('#sample > select:first').clone().show().appendTo('#sample');
$("<br/>").appendTo('#sample');
});
But although I kind of find the reason, I am still confused in solving it. Is there any solutions around this?
You're dynamically creating your elements, therefore you need a dynamic event delegation:
Dynamic Delegation works like:
$("staticElement").on("someevent", "dynamicElement", function)
and it's used to attach an event to the parent with a renewal look for recently appended child Elements.
To explain, on execution time if you attach an event to some elements directly like: $(".foo").click(fn) or $(".foo").on("click", fn) it will not account for .foo elements added in a later time cause they were not in the .foo collection at the time.
By assigning the event to the static parent, the event Delegation will bubble inversely searching for children (that match the selector argument and are the initiators of the same event trough event.target) that received that event.
In your example:
// static Parent // evt , dynamic
$("#sample").on("change", "> select:last", function() {
$('#sample > select:first').clone().show().appendTo('#sample');
$("<br/>").appendTo('#sample');
});
More details to your question here: http://api.jquery.com/on/#direct-and-delegated-events

What is the difference between on("click",function()) and onclick="function();"?

So if I want something to happen when I click a button I can either do:
<!-- EXAMPLE A-->
<input type="button" onclick="alert('hello world');">
or I can do
<!-- EXAMPLE B-->
<input type="button" id="clickme">
<script>
$('#clickme').on("click",function(){alert('hello world');});
</script>
Or of course any variations (on change, on hover) and shortcuts (.click() .change()) are possible...
Besides the fact that A is shorter, what are the differences? Which is better and why?
I noticed, that when I use .html() to dynamically add an element to the site (like a button) B doesn't work for this newly created button, and I need to use A...
Any insights would be helpful!
<input type="button" onclick="alert('hello world');">
This is the way how inline events are handled. The main reason this is a bad idea is to clearly define the separation of concerns.
HTML - Structure of your page
JS - Your page functionality
This will cause less maintenance issues in the long run and when the system scales in size.
What happens if you have 100 buttons on your page and you want to remove the click event or change it for all of them. It would definitely be a nightmare.
Also you can only define a single event if you bind it inline.
By moving out to a separate file you have a lot of flexibility and you can just make a small change that will affect all the elements on the page.
So the 2nd approach is always better. and the way to go.
By defining the events like below
$('#clickme').on("click",function(){alert('hello world');});
you HTML looks clean sans of any functionality and removes the tight coupling.
In the cases you have a dynamically added, it is true inline events always work but there is a concept called Event Delegation . You attach the event to a parent container that is always present on the page and bind the event to it. When the event occurs at a later time on the element , the event bubbles to the parent which handles the event for you.
For such cases you bind the events using .on passing in a selector
$(document).on('click', '#clickme', function() {
Keep in mind that binding multiple events to a document is a bad idea. You can always use the closestStaticAncestor to bind the events.
The first approach only lets you register one click listener whereas the second approach lets you register as many as you want.
If you want clicks on dynamically added elements to be heard as well, you should use .on(). Here's some code that demonstrates this (jsfiddle):
HTML
<div id="mainDiv">
<span class="span1">hello</span>
</div>
JS
$(document).on("click", ".span1", function () {
$( "#mainDiv" ).append("<span class=\"span1\">hello</span>");
});
$(".span1").click( function () {
console.log( "first listener" );
});
$(".span1").click( function () {
console.log( "second listener" );
});
Notice that first listener and second listener is only printed when clicking on the first hello, whereas a new span gets added when clicking on any of the spans.
Guessing this is your real question:
I noticed, that when I use .html() to dynamically add an element to
the site (like a button) B doesn't work for this newly created button,
and I need to use A...
Simply use the selector in the .on() function, AND USE A CLASS instead of DUPLICATE IDs for multiple elements:
$('document').on("click", ".myButtons", function(){
alert('hello world');
});
Button(s) - change to class (if you use IDs, only the FIRST will be selected):
<input type="button" class="myButtons" />
<input type="button" class="myButtons" />
This is how you should use .on() to attach event handlers to new elements:
https://stackoverflow.com/a/14354091/584192
Difference in works, if you use click() you can add several fn, but if you use attribute only one function will be executed - the last one
HTML-
<span id="JQueryClick">Click #JQuery</span> </br>
<span id="JQueryAttrClick">Click #Attr</span> </br>
Js-
$('#JQueryClick').on("click", function(){alert('1')});
$('#JQueryClick').on("click", function(){alert('2')});
$('#JQueryAttrClick').attr('onClick'," alert('1')" );//this doesn't work
$('#JQueryAttrClick').attr('onClick'," alert('2')" );
If we are talking about performance, in any case directly using is always faster, but using of attribute you will be able to assign only one function.
Try This
Reference

using jQuery to change, only the elements that were loaded via ajax

For each checkbox on the web page, I replace it with a slider that I borrowed from jsfiddle.net/gnQUe/170/
This is done by going through the elements when the document is loaded.
Now the problem is that when more content is loaded via ajax, the new checkboxes are not transformed.
To solve the problem, I used AjaxComplete event to go through all the elements again and replace the checkboxes with sliders.
Now the problem happens that elements that were already replaced, get two sliders. To avoid that I check if the checkbox is hidden and next element is div of class "slider-frame", then don't process the re-process the element.
But I have a lot of other such controls as well, and I am presume I am not the only one that has this problem. Is there another easy way around it?
There exists jQuery live/on( http://api.jquery.com/on/ ) event but it requires an event as an argument? whereas I would like to change the look of my controls when they are rendered.
Another example of the same problem is to extend some controls that are loaded via ajax with jQuerys autocomplete plugin.
Is there a better way to accomplish this other than changing some attributes on the element.
To summarize, on document load I would like to process every element in DOM, but when more elements are loaded via ajax then I want to change only the new elements.
I would assume that when the element's are transformed into a slider, a class is added to them. So just add a not clause.
$(".MySelector").not(".SomeClassThatSliderAddsToElement").slider({});
So in the case of your code do something like this
$('.slider-button').not(".sliderloaded").addClass("sliderloaded").toggle(function(){
$(this).addClass('on').html('YES');
$('#slider').val(true);
},function(){
$(this).removeClass('on').html('NO');
$('#slider').val(false);
});
Since you said you do not want to add anything else, how about you change the toggle function to click.
$(document).on("click", ".slider-button", function(){
var elem = $(this);
elem.toggleClass("on");
var state = elem.hasClass("on");
elem.text(state?"YES":"NO");
elem.parent().next().val(state);
});
Running fiddle: http://jsfiddle.net/d9uFs/

jquery onclick is not working

I am dynamically creating a link, and I am trying to add a click function to it. The links are being added, but the click function is not working. I dont see anything in the console, nor do I get an alert.
var section = $('<section></section>').append('<a class="link" href="#"></a>');
section.find('a.link').attr('title', post.data.permalink)
.text(post.data.title)
.click(function()
{
console.log("function");
alert("hi");
getThread(post.data.permalink);
});
items.push(section[0].outerHTML);
$('#posts').empty().append(items.join(''));
One of the most common mistakes with jQuery. When dynamically adding elements, normal jQuery event handlers don't work, so you need to use .live() to be able to bind events to dynamic elements. This should work:
var section = $('<section></section>').append('<a class="link" href="#"></a>');
section.find('a.link').attr('title', post.data.permalink)
.text(post.data.title)
.live("click", function()
{
console.log("function");
alert("hi");
getThread(post.data.permalink);
});
items.push(section[0].outerHTML);
$('#posts').empty().append(items.join(''));
Notice the use of .live("click", function() { ... }); there? That should solve your problem.
That looks okay. You may try using each() to iterate over that collection. I'm not sure if you can bind even handlers to a jQuery collection like that.
section.find('a.link').each(function(){
$(this).attr('title', post.data.permalink)
.text(post.data.title)
.click(function()
{
console.log("function");
alert("hi");
getThread(post.data.permalink);
});
});
If running this in IE be sure that developer-tools (F12 )are present , otherwise console will be undefined and the call of console.log() will force an error and stops the function from executing.
What else: outerHTML is IE-only, you'll better forget it and never use it.
You don't need to manually join the HTML.
You're binding the event to an element, then taking the HTML of that element and just concatenting it into a string, which is then in turn inserted into the DOM as new elements when you append to #posts.
items is not defined here, but I'm going to go out on a limb and assume it's an array of generated <section>s and etc?
If that's the case, I might be missing something you're trying to do here, but it seems you could just eliminate the whole concatention of HTML and simply append the items array, which would preserve the bound click event.
// Push the element, don't stringify it.
items.push(section);
// Then simply append the "items" elements.
$('#posts').empty().append(items);
Sure, live would probably solve the problem as well, but you certainly can bind events to generated elements then insert them into the DOM. What you cannot do is bind an event to an element then print out it's HTML and insert that into the DOM. Any binding you made with the original element is lost.

JQuery - Appended Links don't work

I have created a dynamic list picker script using Jquery 1.3 and PHP that sends a JSON AJAX request and returns a list of items to choose from. The AJAX call works perfectly returning an array of items that I use Jquery to append them as an unordered list to an empty container DIV. That portion of the process works as expected.
The problem comes from the fact that from that list of items, I'm drawing them as links whose clicks are handled by a rel attribute. Here's an example:
<a rel="itemPick" id="5|2" href="#">This is the link</a>
The JQUERY handler looks like:
$('a[rel=itemPick]').click(function () {
code here...
});
These links and click handlers work fine when the page loads, but when they are appended to the container DIV, the click event does not get picked up. I don't want to have to refresh the entire HTML page again, so is there something I need to do in addition to append() to get JQUERY to recognize the newly added links?
When you use the jQuery.click method, it's looking for all of the "a" elements that currently exist on the page. Then, when you add a new "a" element, it has no knowledge of that click event handler.
So, there's a new event model in jQuery that allows you to bind functions to all current and future elements called Live Events. You can use Live Events the same way that you use normal event binding, but they will work for all future elements specified. So, you can simply switch your binding logic to:
$('a[rel=itemPick]').live('click', function () {
//code here...
})
$('a[rel=itemPick]').live("click", function (){ code here... });
Do you bind the event after adding the links?

Categories