JQuery not working on inserted/inject DOM element - javascript

I am still a bit new to JS & JQuery, so please excuse what may be a simple and stupid question.
Background:
I have a div on my page that holds several divs (#idle-variable). On click of the top level div, it basically shows the other divs (#addvariable). Nothing more than display: none; and .show(). Easy. On another action within that div (change of drop down), I essentially want to inject/insert that top level div (#idle-variable) underneath the first instance.
Issue:
Essentially, the .click function is not working on my newly inserted div. This may be because the two div's share the same ID, BUT I have a sneaky suspicion that it's not recognized in the DOM. A friend of mine said something about I have to "re-run" my jquery in order for it to be readable in the DOM.
Question:
How can i make this work properly? I want to be able to add a dynamic number of these idle-variables to the page and I need to make sure my .click function works for all added DIVS.
$(function(){
$('#idle-variable').click(function(event) {
$("#addvariable").show(400);
});
});
//create variable in db & show value entry
$("#variabletype").change(function() {
$("#varholder").css("display", "inline-block");
$.ajax({
type: "POST",
url: "/myphpfile.php",
data: {"variabletype": $("#variabletype").val()},
success: function(){
$( "#idle-variable" ).after("<div id="#idle-variable>content</div>");
}
});
});

Well to make the code work it would need to use on and ids are only supposed to be on one element. If it can be on the page multiple times you need to use classes.
$(document).on("click,'#idle-variable', function(event) {
$("#addvariable").show(400);
});
you should be using classes
$(document).on("click,'.idle-variable', function(event) {
//$("#addvariable").show(400); //not sure how this relates to the clicked element.
$(this).find(".addvariable").show(400); //if it is a child
});
You also have a typo in your code with quotes.

The ID based selector will be applied to the first element only.
See the example here http://jsfiddle.net/9GN2P/2/
If you are looking to bind same event handler to multiple elements, definitely go with the class based approach, instead of ID based approach.
And, you are expecting event handler to work with dynamically created elements as well. If you are using older versions of jquery, use the live method like
$('yourselector').live('click',function(){
});
Since live is deprecated and if you are in a new version, use the 'on' method
$('containerselector').on('click','yourselector',function(){
});
Editing to answer your comment:
To create dynamic element and append to DOM, you can follow the bellow pattern. Here, I will create a DIV with id "newID", class "newClass", content "NEW DIV!!" and a click event handler for it. And it will be pushed into another div with id 'containerID'
$('<div />',{
id:'newID',
'class':'newClass',
text:'NEW DIV!!',
click:function(){alert('hi');}
})
.appendTo('div#containerID');
This is just a demo.

Related

How to target a specific element without knowing it's class or id, but do have all DOM details of the element

To place an external widget without having to let non-technical people paste embed code on every desired spot on a webpage, I'm working on a visual div and p tag selector where people can just pinpoint the desired element(s).
When people hover over an element, it will show a red border to show them what's selected.
For us to place the widget, normally we would target by class or id. However, the class / id should be unique for it to work and unique classes for a random div / p tag is pretty rare.
Via a piece of jquery code:
$(document).on('mouseenter mouseleave', '.sj-highlight',
function (e) {
}
I can get the DOM details about the selected element.
Is there a way I can target the highlighted element by using some data from the DOM details and if yes how?
Tried the code above but just don't know much about DOM selecting possibilities.
To make the whole highlight per element possible, I wrote this:
$( document ).ready(function() {
$('div, p').each(function(i){
$(this).addClass('sj-highlight sjhighlight'+i+'');
$(this).attr('data-sj', 'sjhighlight'+i+'');
});
$(document).on('mouseenter mouseleave', '.sj-highlight', function (e) {
var sjhighlighter = $(this).attr("data-sj");
// hide other highlights
$('.sj-highlight').css("border","2px solid transparent");
if(e.type == 'mouseenter')
{
$('.'+sjhighlighter+'').css("border","2px solid #ff0000");
}
});
The end result would be to somehow target the selected elements with the DOM instead of a class or id.
From the pieces that i put together i think if you can get to the element using
$(document).on('mouseenter mouseleave', '.sj-highlight',
function (e) {});
that means you already have it, because $(document).on() form works for dynamically added elements (that means even if you add element dynamically it still works properly), you can use :
var elementClass = $(this).attr('class');
and you have complete control over the element from there.
And you have also all possibility over its children or it parent which returned as dom elements objects.
I think that your question need a little bit of clarification too.
Here is an option that I used when trying to target elements without the ID or Class. You first need to figure out what each of these highlighted elements have in common. Either it be a specific color, element hierarchy, etc. Then you could use the filter() jquery to find all elements with that spec. This is what I used.
/*select an element that contains this piece of code your trying to target*/
$('#Parent_container').filter(function() {
/*here you will specify what you're trying to identify or target*/
return $(this).find('div[class="sj-highlight"]').length >0;
/*optional but you can create a condition to add code or do whatever you want*/
}).find('div[class="sj-highlight"]').after('<p>some stuff</p>');
Hope that helps. It might give you some idea of what options you have.

Assigning JQuery On Click Function in For Loop

I have a function that dynamically creates div elements based upon whatever input is given, and lets them choose certain items by clicking on each div. I have it so that if the div is clicked, a function (named checkToggle) is called that makes it looks like it is selected and adjusts some related variables. There is a checkbox in the div element that is toggled by this function (hence its name). Long story short, I had to jump through some hoops to get it to work, most of which I don't even remember. Please don't ask me about that.
The point of this question is this. I initially used the following JavaScript code to run the function when the checkbox was clicked. It was assigned by the main function, which created these div elements using a for loop.
document.getElementById(`${itemID}-checkbox`).onclick = function() {
checkToggle(`${itemID}-checkbox`);
};
This works, but I wanted to try to convert all of my onClick functions to JQuery. Here is the JQuery alternative I created.
$(`${itemID}-checkbox`).on(`click`, function() {
checkToggle(`${itemID}-checkbox`);
});
While the code itself seems to be fine, it does not work. It seems as if JQuery functions cannot be created like this in a for loop or something. It is applied after the element is created and put in its place, so I don't think it has anything to do with the element not being ready. I am also having the same issue with 2 other similar cases. Any idea as of why this isn't working?
Let me know if more information is needed and if so, what kind of information is needed.
You need to update the selector to Target HTML id using the # character. Simply prepend the character to the query:
$(`#${itemID}-checkbox`).on(`click`, function() { checkToggle(`${itemID}-checkbox`); });
It would also apply to DOM methods querySelector or querySelectorAll as well.
Hopefully that helps!

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/

Recursive jQuery function to amend select option values

I have a form that I am trying to alter with jQuery. Basically, my form has two elements and I need to change the value of the first option in each of them. However, there is an "add more" option that uses AJAX to dynamically generate another element that also needs changed. This add more button can be clicked an unlimited amount of times.
Right now I have this:
$(document).ready(function(){
$("#myname-0-field option:first").val("None");
$("#myname-1-field option:first").val("None");
});
This works fine, but once the "add more" button is clicked, I have more elements called "#myname-2-field", "#myname-3-field", "#myname-4-field" etc. These obviously aren't affected by adding another line into my jQuery as the document has already loaded when they are added.
So the real question is, can someone point me in the right direction of writing a function that can react when the new element is added and change it. If possible, I'm also looking for the function to be aware and look for "#myname-X-field option:first" for tidyness.
use live() function
Then using each function set value
From the jQuery API look live function
Maybe you could add class to your element, so that finding particular element would be easier and it would not add event to other similar elements.
In the example I have a Li with class
$('li.myClass').live('click', function() {
$(this).val(); // this is the getter for clicked value
$(this).val("some_value_here"); // this is the setter for clicked value
});
Now you can add more elements (that has myClass class) and it will have a click event.
Btw. if you know that all elements are inside some container (div for example) then you can write more efficient jQuery using delegate.
$('#container_id').delegate('li.myClass', 'click', function () {
});
This is more efficient because it looks your new elements only under "containter" not from the whole DOM structure.

Using jQuery on dynamically added content

I am newbie to jQuery and javascript. In my application I have a list of users. When a particular user is clicked from the list, a div element is replaced with details about the user dynamically. When another user is clicked, again I replace the same div element with this user details. So at a time only one user details can be seen.
I use jquery, so my code to the above description looks like.
$('table#moderate_users tr').click(function() {
$.get('/moderate/user/'+uid, function(data){ $('div.user_info').html(data);
});
});
This works perfect and the content is inserted dynamically.
I have a dropdown(html select tag) in the dynamically added content. So I get the dropdown only when i click on a user from the list and it changes repectively when I click on another user. I wanted to find the value of the select tag using jquery whenever it is changed. So I wrote
$('select#assign_role').change(function(){
alert(this.val());
});
Since this dropdown is added after document.ready, adding this script inside document.ready function never worked. I also tried to insert the above script along the with the user details which is dynamically added.For my surprise this script is not inserted into the document at all, while the rest of the HTML content are inserted perfect. I am not aware if i can add insert javascript after the document has loaded. I am not aware how i could use jQuery to find out the value of the select tag which is added dynamically.
Thanks.
you want jQuery's "live" functionality:
$('select#assign_role').live('change',function(){
alert($(this).val());
});
also notice I changed alert(this.val()); to alert($(this).val()); considering that this inside a jQuery event handler references the actual dom element, not a jQuery object.
From the looks of your code, it seems that you are inserting a chunk of HTML into that div. So even if you wire your event to the dropdown after the page load, it will not work, since all of your event binding will be ignored when you insert new HTML code into div.
Try moving your code inside the function that inserts HTML. Something like this:
$('table#moderate_users tr').click(function() {
$.get('/moderate/user/'+uid, function(data){
$('div.user_info').html(data);
$('select#assign_role').change(function(){
alert(this.val());
});
});
});
On IE the live function doesn't work for onchange on <select> elements.
http://www.neeraj.name/blog/articles/882-how-live-method-works-in-jquery-why-it-does-not-work-in-some-cases-when-to-use-livequery
You will need to either add the select then do a setTimeout and then bind with the jquery.bind type of functionality, or, what I have done, is when you create the element then just set the onchange event handler there directly.
If you don't need to support IE then the live function works great.

Categories