Accessing dynamically appended div elements in jQuery - javascript

I need a suggestion on below scenario.
I have an object of items and dynamically building a html object as follows:
$.each(item,function(k, iteminner) {
html += '<td><div id="outerdiv">' + iteminner.Name + '</div>';
html += '<div id="clickme"></div></td>';
});
A table is built in this format, where each box will contain a name and button in each td. When a user clicks on a button of a cell I want to show the name respectively.What is it that I am missing here?
$('#clickme").click() {
alert($("#outerdiv").iteminner.name);
}
Assuming that id is unique for both the divs, like id="outerdiv" + k , how do I access element present in second cell, when second div id="clickme" + 2 is clicked?

ID's they have to UNIQUE
// Use class instead
$.each(item, function(k, iteminner) {
html += '<td><div class="outerdiv">' + iteminner.Name + '</div>';
html += '<div class="clickme"></div></td>';
});
// You need to have event delegation here as a direct onclick wont be binded for the dynamically created .clickme
$(document).on("click", ".clickme", function(){
// You need to fetch the html of .outerdiv, so traverse to it first.
var _html = $(this).closest("td").find(".outerdiv").html();
alert(_html);
});

Firstly you are appending multiple elements with the same id to the DOM, which is invalid. You should change your HTML to use classes, like this:
$.each(item, function(k, iteminner) {
html += '<td><div class="outerdiv">' + iteminner.Name + '</div><div class="clickme"></div></td>';
});
From there you need to use a delegated event handler on the .clickme elements (as they are dynamically created after the DOM has loaded) to traverse the DOM and find their sibling .outerdiv. Try this:
$(document).on('click', '.clickme', function() {
var name = $(this).siblings('.outerdiv').text();
// do something with name here...
});
Note that I used document as the primary selector above. Ideally you should use the nearest static parent element - I would suggest you use the same selector you use to append the html variable to.

Related

Jquery add data to html before adding to DOM

I am building html on the fly need to add data before I add it to DOM. Since I am looping thru' lot of information, I would like to add the relevant data info along with the dom I am building instead of adding the html and then looping thru again to add the data.
result.forEach(function(record) {
html += '<div id ="' record.ID + '">test content </div> ';
//add data to above
});
I can do another loop here after adding it to DOM
$(body).append(html);
testresult.forEach(function(record) {
$("#" +record.ID).data(record);
});
Instead of concatenating strings to piece together your HTML, you may way to try something like this:
result.forEach(function(record) {
$('.selector').append(function () {
var $div = $('<div></div>');
$div.attr('id', record.testID).text('some text');
return $div;
});
});
This creates a new div jquery object for each item in result. You can use the record object to add attributes, data, text, etc to you object. It will be added the DOM when the callback passed into .append returns your new jquery DOM object.
Start trying to use jQuery to create your html elements so you can take fully advantage of jQuery and its plugins.
Ex:
var div = $("<div></div>") // create the element
.text("test content") // change the inner text
.attr("id", record.testID); // set the element id
div.appendTo("body");
You can check out [http://www.w3schools.com/jquery/] as a great source for learning jQuery.
You have quotes problem in the following line :
html += '<div id =record.testID' + '>test content </div> ';
________^______________________^___^_____________________^
You should fix that using double quotes because as it's now the string will be considered as '<div id =record.testID'.
html += '<div id="'+record.testID+'">test content </div>';
Or you could use separated definition :
$.each(result, function(index,record) {
var div = $('<div>test content</div>');
div.attr('id', record.testID);
div.data('test', record.testDATA);
$('body').append(div);
})
Hope this helps.
var result = [{testID: 1,testDATA: 'data 1'},{testID: 2,testDATA: 'data 2'},{testID: 3,testDATA: 'data 3'}]
var html='';
$.each(result, function(index,record) {
var div = $('<div>test content</div>');
div.attr('id', record.testID);
div.data('test', record.testDATA);
console.log(div.data('test'));
$('body').append(div);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Refer to element ID set dynamically through Javascript

I am setting the ID of an element, say a button, dynamically. An example is given below (the code may have syntactic errors, I am merely trying to explain my problem).
function myFunc(){
var counter = 0;
return function(){
counter += 1;
var rowContent = '<div>';
rowContent += '<button type="button" class="btn btn-default" id="button"' + counter + '></button>';
rowContent += '</div>';
$('#someElement').append(rowContent);
};
}
Now I want to associate a click event with the button. I need to mention the ID element when associating the event with the button (e.g. $('#myID')). But since the ID is being set dynamically, I do not know for sure what the ID may be. Could someone tell me how I could refer to the dynamically-set ID of the element when associating an event with it? Thanks in advance!!
Delegate the event to the parent element rowContent.
$('#someElement').append(rowContent);
$('button', rowContent).on('click', function(e) {
// button element in the 'rowContent' context
}
Delegating it to #someElement will also work, unless you'll be putting multiple buttons with different click handlers inside of there.
You should better be using event delegation in such case:
$('#someElement').on('click','[id^=button]',function(){
//do stuff
});
You can easily define your own custom attribute and select it with this attribute as:
rowContent += '<button type="button" mybtn="" class="btn btn-default" id="button"' + counter + '></button>';
and here is the selector:
$("div[mybtn]")

add and remove elements from form, 1st click works, subsequent clicks dont

I am trying to add/remove an element to a form based on a checkbox in a previous part of the form. My problem is, the first time a user clicks on anything in checkContact, the form is appended correctly. If the user unchecks the box, it is removed correctly. When the user re-clicks the checkbox, the element is not added..
$('.checkContact').click(function(){
var addInfo = "<div class='middleRow'><input type='text' id='"+val+"_name[]' name='"+val+"'_name[]'></div>";
if($(this).is(':checked'))
{
alert(addInfo);
$('#'+divId).append(addInfo);
}
else
{
$('#'+divId).detach();
// i have also tried .remove();
}
fiddle:
Fiddle
In the else part, you are removing the element $('#' + divId) from the dom tree instead of removing its content. You have to only empty the container element because in the if block you are adding the target markup to the container element.
$('.checkContact').click(function () {
var val = $(this).val();
var divId = val + '_div';
var addInfo = "<div class='middleRow'><input type='text' id='" + val + "_name[]' name='" + val + "'_name[]'></div>";
if (this.checked) {
//alert(addInfo);
$('#' + divId).html(addInfo);
} else {
//you are removing the container instead of removing its content
$('#' + divId).empty();
}
});
Demo: Fiddle
When you uncheck the box, you remove name_div from the DOM with .detach. So when you click the box again, the selector doesn't find anything, so there's nothing to append to.
Change .detach() to .empty()
DEMO
But perhaps a better method would be to hide and show the DIV, rather than add and remove the content.
In your code you have used detach() or empty(), it would remove the element from the DOM and after that you will not be able to insert html by using .html() method. Instead of using detach() or remove() you have to use .empty() or .html(''), this will keep the element in DOM, so you can again and again append the element.
$('.checkContact').click(function(){
var addInfo = "<div class='middleRow'><input type='text' id='"+val+"_name[]' name='"+val+"'_name[]'></div>";
if($(this).is(':checked'))
{
alert(addInfo);
$('#'+divId).append(addInfo);
}
else
{
$('#'+divId).html('');
//or $('#'+divId).empty();
}
});
see here:
http://jsfiddle.net/WYmVU/

Dynamically assign id to div and use that to call jquery slide effects

I am reading contents from JSON file and adding to div with unique IDs. I need to call jquery slide down effects to each div. Lets us consider the case, on clicking (div id=A1) it should slide down and show (div id=B1), in that way I have div with IDs A(1..N) and B(1..N).
var i=1;
$.each(items, function (index, item) {
$(document).ready(function(){
$("#A"+i).click(function(){
$("#B"+i).slideToggle();
});
});
$("#allContents").append('<div id="A'+i+'">' + item.Name + '</div>');
$("#allContents").append('<div id="B'+i+'">' + item.Details + '</div>');
i++;
});
This is the closest code I could derive to, but it is not working. If anyone could help me fix or suggest a better way to get this thing working it would be great. Thanks a lot!
$('#allContents').on('click', 'div[id^=A]', function() {
$('div#B' + this.id.replace('A','')).slideToggle();
});
A little explain
div[id^=A] point out those div whose id start with A.
this.id retrieve the id of clicked element.
this.id.replace('A','') replace A form the id and get the numeric index which equal to index of B.
$('div#B' + this.id.replace('A','')) point to element id=B1, id=B2 and so on.
Full code
// you can bind event handler outside ot loop
$('#allContents').on('click', 'div[id^=A]', function() {
$('div#B' + this.id.replace('A','')).slideToggle();
});
$.each(items, function(index, item) {
$("#allContents").append('<div id="A' + i + '">' + item.name + '</div>');
$("#allContents").append('<div id="B' + i + '">' + item.Details + '</div>');
i++;
});
Working Sample
Note
As you're creating div from A(1..N) and B(1..N) dynamically so you need delegate event handler (aka live event).
Syntax of jQuery .on() for delegate event is like following:
$(container).on(eventName, target, handlerFunction)

jquery, add div with class definition

So I see here how to add a div and here how to add a class but I'm having trouble combining the two. I want to generate a whole bunch of div's with a specific class and id within the div sparkLineContainer.
I have the containing div
<div id="#sparkLineContainer"></div>
and I want to add a bunch of the following to it
<div id="#sparkLineContainer">
<div class="sparkLines" id="id1">Some stuff here</div>
<div class="sparkLines" id="id2">Some stuff here</div>
<div class="sparkLines" id="id3">Some stuff here</div>
// and so on
</div>
snippet - I didn't make it very far, I'm stumped
$('#sparkContainer').add("div"); \\ How do I add the id and class to this div?
\\ And as a repeat the function will it overwrite this?
The function I'm trying to do this with.
function renderSparklines (array1, sparkLineName, id) {
// array1 is the data for the spark line
// sparkLineName is the name of the data.
// Turn all array values into integers
arrayStringToInt(array1);
// Create new div of class sparkLines
$('#sparkContainer').add("div")
// Render new spark line to
$('.sparkLines').sparkline(array1, {width:'90px'});
var htmlString = ""; // Content to be added to new div
// GENERATE LITTLE SPARK BOX
htmlString +=
'<font class = "blueDescriptor">' + sparkLineName + '</font>'+
'<br>'+
'<font class = "greyDescriptorSmall">Ship to Shore</font>'+
'<br>'+
'<font class = "blackDescriptorSparkLine">' + array1[array1.length-1] + '</font>'+
'<font class = "greenDescriptorSparkline">(' + (array1[array1.length-1] - array1[array1.length-2]) + ')</font>' +
'<br>';
$('.sparkLines').prepend(htmlString);
}
add does not do what you think it does. You are looking for append or something similar.
You can create the div first and define its attributes and contents, then append it:
var $newDiv = $("<div/>") // creates a div element
.attr("id", "someID") // adds the id
.addClass("someClass") // add a class
.html("<div>stuff here</div>");
$("#somecontainer").append($newDiv);
You need .append or .prepend to add a div to the container. See my version below,
var $sparkLines = $('.sparkLines');
$("#sparkLineContainer")
.append('<div id="id' +
($sparkLines.length + 1) +
'" class="sparkLines">Some Stuff Here</div>')
Also I noticed that you have id of the div as #sparkLineContainer. You should change it as below,
<div id="sparkLineContainer">
...
DEMO
You can add a div or any other tag along with class like:
$('<div/>',{ class : 'example'}).appendTo("p");
Probably the easiest way is to just modify the innerHTML:
$("#sparkLineContainer").append('<div class="sparkLine" id="id1"></div>');
There's other ways as well, but this is the method I generally use.

Categories