jQuery children of cloned element not responding to events - events

Summary
I am using jQuery to clone a div ("boxCollection") containing groups ("groupBox") each of which contains a set of inputs. The inputs have change events tied to them at $(document).ready, but the inputs inside the cloned divs do not respond to the event triggers. I can not get this to work in IE7, IE8, or FF3.
Here is my sample code:
HTML:
<div class="boxCollection"><div class="groupBox" id="group_1"><input type="text"></input></div></div>
jQuery events:
$(".groupBox[id*='group']").change(function(){
index = $(this).attr("id").substring(6);
if($("input[name='collection_"+index+"']").val() == "")
{
$("input[name='collection_"+index+"']").val("Untitled Collection "+index);
}
});
jQuery clone statement:
$(".boxCollection:last").clone(true).insertAfter($(".boxCollection:last"));

Use live() to automatically put event handlers on dynamically created elements:
$(".groupBox[id*='group']").live("change", function() {
...
});
You appear to be putting a change() event handler on a <div> however (based on your sample HTML). Also, I would recommend not using an attribute selector for this. You've given it a class so instead do:
$("div.groupBox ...")...
Lastly, you are trying to give each text input a unique name. You don't say what your serverside technology is but many (most?) will handle this better than that. In PHP for example you can do:
And $_POST will contain an element "box" with an array of three values.

I'm not sure if this will work, but I'm going to give it a shot and say that you need to assign live events
$(".groupBox[id*='group']").live('change', function() { });
You'll probably have a problem with change and live in IE6/7, so I advise you to use the livequery plugin to resolve that issue.

Related

The view area of ckEditor sometimes shows empty at the start

I am using the following directive to create a ckEditor view. There are other lines to the directive to save the data but these are not included as saving always works for me.
app.directive('ckEditor', [function () {
return {
require: '?ngModel',
link: function ($scope, elm, attr, ngModel) {
var ck = ck = CKEDITOR.replace(elm[0]);
ngModel.$render = function (value) {
ck.setData(ngModel.$modelValue);
setTimeout(function () {
ck.setData(ngModel.$modelValue);
}, 1000);
}; }
};
}])
The window appears but almost always the first time around it is empty. Then after clicking the [SOURCE] button to show the source and clicking it again the window is populated with data.
I'm very sure that the ck.setData works as I tried a ck.getData and then logged the output to the console. However it seems like ck.setData does not make the data visible at the start.
Is there some way to force the view window contents to appear?
You can call render on the model at any time and it will simply do whatever you've told it to do. In your case, calling ngModel.$render() will grab the $modelValue and pass it to ck.setData(). Angular will automatically call $render whenever it needs to during its digest cycle (i.e. whenever it notices that the model has been updated). However, I have noticed that there are times when Angular doesn't update properly, especially in instances where the $modelValue is set prior to the directive being compiled.
So, you can simply call ngModel.$render() when your modal object is set. The only problem with that is you have to have access to the ngModel object to do that, which you don't have in your controller. My suggestion would be to do the following:
In your controller:
$scope.editRow = function (row, entityType) {
$scope.modal.data = row;
$scope.modal.visible = true;
...
...
// trigger event after $scope.modal is set
$scope.$emit('modalObjectSet', $scope.modal); //passing $scope.modal is optional
}
In your directive:
ngModel.$render = function (value) {
ck.setData(ngModel.$modelValue);
};
scope.$on('modalObjectSet', function(e, modalData){
// force a call to render
ngModel.$render();
});
Its not a particularly clean solution, but it should allow you to call $render whenever you need to. I hope that helps.
UPDATE: (after your update)
I wasn't aware that your controllers were nested. This can get really icky in Angular, but I'll try to provide a few possible solutions (given that I'm not able to see all your code and project layout). Scope events (as noted here) are specific to the nesting of the scope and only emit events to child scopes. Because of that, I would suggest trying one of the three following solutions (listed in order of my personal preference):
1) Reorganize your code to have a cleaner layout (less nesting of controllers) so that your scopes are direct decendants (rather than sibling controllers).
2) I'm going to assume that 1) wasn't possible. Next I would try to use the $scope.$broadcast() function. The specs for that are listed here as well. The difference between $emit and $broadcast is that $emit only sends event to child $scopes, while $broadcast will send events to both parent and child scopes.
3) Forget using $scope events in angular and just use generic javascript events (using a framework such as jQuery or even just roll your own as in the example here)
There's a fairly simple answer to the question. I checked the DOM and found out the data was getting loaded in fact all of the time. However it was not displaying in the Chrome browser. So the problem is more of a display issue with ckEditor. Strange solution seems to be to do a resize of the ckEditor window which then makes the text visible.
This is a strange issue with ckeditor when your ckeditor is hidden by default. Trying to show the editor has a 30% chance of the editor being uneditable and the editor data is cleared. If you are trying to hide/show your editor, use a css trick like position:absolute;left-9999px; to hide the editor and just return it back by css. This way, the ckeditor is not being removed in the DOM but is just positioned elsewhere.
Use this java script code that is very simple and effective.Note editor1 is my textarea id
<script>
$(function () {
CKEDITOR.timestamp= new Date();
CKEDITOR.replace('editor1');
});
</script>
Second way In controller ,when your query is fetch data from database then use th
is code after .success(function().
$http.get(url).success(function(){
CKEDITOR.replace('editor1');
});
I know, that this thread is dead for a year, but I got the same problem and I found another (still ugly) solution to this problem:
instance.setData(html, function(){
instance.setData(html);
});

jQuery 'on' not registering in dynamically generated modal popup

I was under the impression that jQuery's on event handler was meant to be able to 'listen' for dynamically created elements AND that it was supposed to replace the behavior of live. However, what I have experienced is that using on is not capturing the click event whereas using live is succeeding!
The tricky aspect of my situation is that I am not only dynamically creating content but I'm doing it via an AJAX .get() call, and inserting the resultant HTML into a modal .dialog() jQueryUI popup.
Here is a simplified version of what I was trying to accomplish (wrapped in $(document).ready(...) ):
$.get("getUserDataAjax.php", queryString, function(formToDisplay) {
$("#dialog").dialog({
autoOpen: true,
modal: true,
buttons...
}).html(formToDisplay);
});
$(".classThatExistsInFormToDisplay").on("click", function() {
alert("This doesn't get called");
});
From the documentation for on I found this which which was how I was approaching writing my on event:
$("p").on("click", function(){
alert( $(this).text() );
});
However, for some reason, live will work as I expect -- whereas on is failing me.
This isn't a question for "how can I make it work" because I have found that on will succeed (capture clicks) if I declare it inside the function(formToDisplay) callback.
My question is: what is wrong with on that it isn't finding my dynamically created elements within a modal popup? My jQuery instance is jquery-1.7.2. jQueryUI is 1.8.21.
Here are two jsFiddles that approximate the issue. Click the word "Test" in both instances to see the different behavior. The only difference in code is replacing on for live.
Where the click is captured by live.
Where the click is NOT captured by on (click 'Test - click me' to see nothing happen).
I realize I may just be using on inappropriately or asking it to do something that was not intended but I want to know why it is not working (but if you have something terribly clever, feel free to share). Thanks for your wisdom!
Update / Answer / Solution:
According to user 'undefined', the difference is that on is not delegated all the way from the top of the document object whereas live does/is.
As Claudio mentions, there are portions of the on documentation that reference dynamically created elements and that what you include in the $("") part of the query needs to exist at runtime.
Here is my new solution: Capture click events on my modal dialog, which, although it does not have any content when the event is created at runtime, will be able to find my content and element with special class that gets generated later.
$("#dialog").on("click", ".classThatExistsInFormToDisplay", function() {
... //(success! Event captured)
});
Thanks so much!
live delegates the event from document object, but on doesn't, if you want to delegate the event using on method, you should delegate the event from one of static parents of the element or document object:
$(document).on("click", ".clickHandle", function() {
alert("Content clicked");
});
The problem is that the element to which you attach the event has to exist.
You have to use on like this to capture clicks on p tags created dynamically
$("#existingContainerId").on("click", "p", function(){
alert( $(this).text() );
});
if you have no relevant existing container to use, you could use $("body") or $(document)
If selector is omitted or is null, the event handler is referred to as direct or directly-bound. The handler is called every time an event occurs on the selected elements, whether it occurs directly on the element or bubbles from a descendant (inner) element.
When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.
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. Or, use delegated events to attach an event handler, as described next
Take a look to section Direct and delegated events here for more details

how to access the id of div which is loaded through ajax

I have button with id = new which loads the new page
$("#new").click(function(){
$('#message_area').load('new.php');
});
There is a button in new.php which sends message to database. But i have a problem with it , it only works for first time when page loads if i navigate to some other links via ajax and again load new.php using above code then send button in new.php does not work i have to refresh the page then it works. I think its because the send button in new.php is added after DOM is created for first time .
Please help Thanks in advance ..
You will need to post more details of your markup for a more accurate answer, but the general idea is to use event delegation. Bind the event handler to an ancestor of the button that does not get removed from the DOM. For example:
$("#message_area").on("click", "#yourButton", function() {
//Do stuff
});
This works because DOM events bubble up the tree, through all of an elements ancestors. Here you are simply capturing the event higher up the tree and checking if it originated from something you are interested in (#yourButton).
See jQuery .on for more. Note that if you're using a version of jQuery below 1.7, you will need to use delegate instead.
//jquery >= v1.7
$("body").on('click', '#new', function(){
$('#message_area').load('new.php');
});
//jquery < v1.7
$("#new").live('click',function(){
$('#message_area').load('new.php');
});
$("#new").live("click", function(){
$('#message_area').load('new.php');
});
just realized this was deprecated-- should be using on instead.. my bad.
To manage dynamically created elements like this, you need to use .on() (jQuery 1.7 and above) or .delegate() (jQuery 1.4.3 and above) to assign the events. Seems everyone has beaten me to the code, but I'll post this for the links to the functions.

Dynamic combo and mootools get method doesn't work in IE8

I have a problem with the Mootools get method and IE8. This is the thing.
I have a select combo that loads dynamically the options with a Request.HTML
HTML:
<select name="model" id="model" class="customSelectModel">
<option>Modelo</option>
</select>
Javascript:
var req = new Request.HTML({
method: 'get',
url: loadModels,
data: "model="+model,
update: $('model'),
}).send();
Also, the select has a custom style, with this: http://vault.hanover.edu/~stilson/simpleselectstyle/
The problem is when I load the content of model, IE throw me an error:
Object doesn't support this property or method.
I don't know why, but
span.addEvent('change',function(){
span.set('text',this.options[this.options.selectedIndex].get('text'));
});
does not work with IE8 (as usually, it works perfectly with the other browsers) . I'm using Mootools 1.3.2
Any ideas? Thanks a lot.
you cannot update <select> elements content via innerHTML in a cross-browser fashion, which the update: $("model") will try to do.
I would suggest refactoring via an onComplete: function() {} where you:
delete all child elements of model
iterate through options elements sent via HTML and inject them into the model
call whatever method your custom styling provides (if it has any) to freshen object members for model and fireEvent("change") to highlight your new selected choice for scripting, if you need it.
for your second question.
this.options.get("value") returns selected value.
if its a multiple select, it can have more than 1 value.
mootools provides selectel.getSelected() which returns an array of options you can iterate to get text from. hence:
selectel.getSelected().get("text") will return ["sometext"] or ["sometext1", "sometext2"] on a multiple select.

jQuery: Can I automatically apply a plug-in to a dynamically added element?

I'm in the process of converting my web app to a fully AJAX architecture.
I have my master page that is initially loaded and a div container that is loaded with dynamic content.
I created a few jQuery plugins that I apply to certain elements in order to extend their functionality. I'd normally call the functions as follows during each page load:
$(document).ready(function () {
// Enable fancy AJAX search
$(".entity-search-table").EntitySearch();
});
This would find the appropriate div(s) and call the plugin to enable the necessary functionality.
In an AJAX environment I can't just apply the plugin during the page load since elements will be added and removed dynamically.
I'd like to do something like this:
$(document).ready(function () {
// Enable fancy AJAX search
$(".entity-search-table").live("load", function () {
$(this).EntitySearch();
});
});
Question: Is there any way that I can trigger an event when a <div> or other element that matches a selector is added to the DOM?
It seems incredibly wasteful to activate the plug-in every time an AJAX request completes. The plug-in only needs to be applied to the element once when it is first added to the DOM.
Thanks for any help!
Yes - take a look at liveQuery. Example:
$('.entity-search-table').livequery(function(){
$(this).EntitySearch();
});
It seems incredibly wasteful to activate the plug-in every time an AJAX request completes. The plug-in only needs to be applied to the element once when it is first added to the DOM.
You can get the best of both worlds here, for example:
$("#something").load("url", function() {
$(".entity-search-table", this).EntitySearch();
});
This way it's only applying the plugin to the .entity-search-table elements you just loaded, since we specified a context to $(selector, context) to limit it.
The DOM 2 MutationEvent is what you really want, but unfortunately it isn't supported by IE. You'll need to either use live()/ delegate() binding in the plug-in, or (as I did when I had to work around this) use callbacks from your AJAX loaders indicating the scope of what has changed.
Use the live binding in your plugin code directly
jQuery.fn.EntitySearch = function() {
this.live(..., function(){ your plugin code });
return this;
}

Resources