I have some code that creates an accordion with a select2 element which has a class called docType. I also have jquery code to trigger an event on selecting a value of the jquery element. While this works for select2 elements that already exist on the page load, it doesn't trigger for dynamically added elements. Here is my on change code:
$('.docType').on('change', function() {
// the code inside should be firing for dynamically added elements
}
Does anyone know why this way isn't working?
Use event delegation for dynamically added elements.
$(document).on("change",".docType", function() {
Us the 'on' method to delegate events. This will add a handler to dynamically generated elements.
$(document).on("change",".classnameyouarewatching", function() {
//Your code
}
on method definition
If your elements are being dynamically loaded, you'll need to use something more like what's below. For instance, say you're dynamically generating via AJAX or something similar the following input element:
<input type="text" class="text_element" value="some value">
To add event handlers to that element try using JS like this:
<script type="text/javascript">
$(document).on('change', '.text_element', function() {
console.log('Element with class "text_element" has changed');
console.log('New value is: ' + $(this).val());
});
</script>
The answer above is correct, but it is not just the 'on' handler that delegates the handling of dynamically generated DOM elements. The actual trick here is to place the handler on the document as it will always exist rather than the element or element class as you have above. It is the handler on document, looking for elements of a class (2nd param of the on event) that gets the job done you're looking for.
I think u need to call find() method for all the select element before firing on change method like below
$(".docType").find(":select").on( ("change", function() { // the code inside });
If it does not work, try JQuery instead of $.
Related
I'm loading some html using jQuery function .load() and everything works fine. The problem is that I need to select some of the dynamic created elements to apply some styles with JS. For example:
$(".new-element-class").datepicker();
I know that dynamically added elements are not part of DOM and that I can trigger events this way:
$("body").on("click", ".new-element-class", function() {});
I have read a lot of answers with that solution but that's not what I need. I want to select and apply a function without having to wait for an event. I also tried find() and it didn't work.
You need to call .datepicker() in the code that adds the new element dynamically. You can do this in the callback function of .load()
$("#element").load("url", function() {
$(this).find(".new-element-class").datepicker();
});
I am dynamically adding a list of anchor tags into a div with the id of join. For some reason, my jQuery handler (is it a handler?) isn't handling the clicks.
$(document).ready(function() {
$("#join").click(function() {
console.log("Clicked");
});
});
"Clicked" is not appearing in my console. I have a big headache now after Googling for about 2 hours.
Thanks in advance.
You can also try this way out, this is the most efficient way as you can have control over the click event.
$(document).ready(function() {
$("#join").on('click',function() {
$('#join').off('click');
console.log("Clicked");
});
});
try
$(document).ready(function() {
$(document).on.('click','#join',function() {
console.log("Clicked");
});
});
Note :this will only detect the first instance of #join element.
you may want to use classes instead of id
you need to use document as the selector to detect generated elements
When you create a handler from a selector, the handler is added to all the elements that match the selector when the selector (and handler) are run. If you subsequently add elements which would NOW match the selector, the handler is not automatically added. Those elements were not present when the selector first ran.
When you add your new elements, add the click handler to those new elements at the time they are added.
It is also strongly recommended not to have multiple elements in the page with the same "id" value. Consider using a class for an indicator of grouping.
As most of us know, once an element has been loaded it is possible to attach an event to it by simply using the normal JQuery events.
The question is, what if I want to create a specific event, and define that an element with a specific class or id, will get that event automatically when they are loaded?
For example:
I have a function that checks whether the input that has been entered is numeric only, and allows only numbers to be entered inside an input.
To do that I add the class "numeric" to the input element.
Normally I would just run a script right after with JQuery or just by using the onkeypressed DOM event to attach that function to it.
However, let's assume I have an ajax request that attaches a new from page, with the class numeric in the proper input elements.
Using the script again using the same class selector will result in the event run 2 times for elements that were loaded earlier.. And for every time I run that script it will add that event over and over...
What I do now, is I used the "unbind" first, and then reattach the event to all elements, and it is working perfectly! But I am looking for more elegant solution.
Any suggestions?
You need to use the .on with event delegation
Syntax
$(parent-selector).on(event,target-selector,callback);
Note: The parent-selector must be parent element which is present in the DOM while binding the event, generally people use document and body, but for the performance you must have the nearest parent possible to the target
Example
$(document).on("click",".button",function(){
alert("Button Clicked");
});
Use the on function to attach event handlers for elements that do not exist.
$(document).on("keypress", ".numeric", function(){
//do something
});
JS Fiddle: http://jsfiddle.net/T34Ph/
I am trying to hide/show a class of elements in a form depending on a drop-down menu choice made by the user. See: http://jsfiddle.net/3FmHK/2/
I am new to js and have two problems, so maybe they are obvious, bear with me.
1) I am modifying by the div id, so only the first element changes (and not in this fiddle for some reason, but it does in the project). However I want all the elements of a class to modify and I haven't been able to make that work. So how do I modify the style="display" for an entire class, rather than a single element?
2) The remove does not work for newly added element, when the form is returned with values in the project, they are removable. Using firebug, the code looks identical for the GET return generated elements vs the user added elements, as far as I can tell. Why does the remove function not work for newly added elements?
I recommend using jQuery for this if you can. You can use the .on() feature to bind actions ot newly created elements and use the class selector to .hide() all classes then .show() the currently selected on by id.
It would look something like this:
jQuery(document).ready( function() {
jQuery(document).on('click', '.classname', function() {
jQuery('.' + jQuery(this).attr('class') ).hide();
jQuery(this).show();
// Or you can use the following to show a specific ID element.
//jQuery('#idtoshow').show();
)};
});
This will hide all elements with the class name. You will need to include the jQuery library before your script. Although I am only using show and hide here, you can use .remove() as long as you bind your action with .on and not just .click. You need .on to bind to newly created elements.
http://api.jquery.com/on/
Hope this helps.
Try:
$(this).parent('div').first().remove();
I'm loading new elements with a form. After the elements are loaded I need to make each one draggable. According to .on doc "Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time."
I've tried oh-so-many variants of .on, .click, etc but so far no luck. I'm currently working with...
$('#parent').on('change', '.thumb', function(event){
alert('loaded');
$('.thumb').draggable();
});
...but, it doesn't attach to the new .thumb element. How can I accomplish this?
Edit: Here's the html...
<input type="file" id="parent" name="files[]" multiple />
<output> //these spans are created after files are selected from 'file'
<span><img class=".thumb" src="..."></span>
<span><img class=".thumb" src="..."></span>
</output>
When you use a plugin that requires binding it's own events and DOM manipulation from within the plugin, delegation methods like on() are useless.
You need to call the draggable() method when you load new elements such as in success callback of ajax.
If you are using load()
$('#myDv').load( url, function(){
/* new html has been inserted now */
/* in case any other active draggables will only search within $('#myDiv') for new elements that need to be called*/
$(this).find('.dragClass').draggable();
})
There isn't enough detail for me to answer this question specifically, so I will attempt to guess what the problem is.
You are binding this function to the event "change" of an element with an id of "parent." The "change" function will only work in certain DOM elements, namely input, textarea, and select. (http://api.jquery.com/change/) This means that the change event will never fire if the element with id "parent" is anything but those three tags.
If this is the problem, I would suggest moving the .draggable() method to the same place you are adding "elements with a form."
Try this:
$('#parent').live('change', '#child', function(event){
alert('loaded');
$('#child').draggable();
});