Finding a specific child div via jquery - javascript

I am trying to find and append some text in a dynamically created parent div
but its not working.
Here is what I have tried.
var mainDiv = "" +
"<div>" +
"<div></div>" +
"<div>" +
"<div class='image-here'></div>" +
"</div>" +
"</div>"; // proper script is in Fiddle
var imageDiv = $(mainDiv).children(".image-here");
$(imageDiv).html("text allocated");
$(mainDiv).dialog();
Here is the Fiddle: http://jsfiddle.net/xBB5x/10166/

Change this:
var imageDiv = $(mainDiv).children(".image-here");
$(imageDiv).html("text allocated");
$(mainDiv).dialog()
to this:
$(mainDiv).dialog().find(".image-here").html("text allocated");
Here is the JSFiddle demo

Related

how to put a button inside div where data is filled dynamically through $.each function

This should be very simple but i am struggling here.
I have a parent div which have multiple child div. These child div are generated according to $.each() function. Number of times function run, num of div get generated.Now, i want to write a server side function on button click but i am unable to list that button in these child div.
<div class="div1">
<div class="div2">
// this is the button which i cant see in my div2 div
<button type="input">follow</button>
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("/Home/GetUsers", null, function(data) {
$(".div1").html("");
$.each(data, function(i, item) {
var html = "<div class='div2'>";
html += "Name: " + item.UserName + "<br />";
html += item.ArticleCount;
html += "<img src='" + item.UserImage + "'height='20px' width='20px'/>"
html += "</div>";
$(".div1").append(html);
});
});
});
</script>
</div>
</div>
Any type of guidance appreciated.
If you'd like to add a button per child div you can do it in this way:
$(document).ready(function() {
var parent = $(".div1");
$.getJSON("/Home/GetUsers", null, function(data) {
parent.html("");
$.each(data, function(i, item) {
var html = "<div class='div2'>";
html += "Name: " + item.UserName + "<br />";
html += item.ArticleCount;
html += "<img src='" + item.UserImage + "'height='20px' width='20px'/>";
html += "<button type='button' class='newButton'>Click Me!</button>";
html += "</div>";
parent.append(html);
});
});
// In order to ensure that the button click is handled no matter when it was
// added, we can delegate the handler to the parent.
parent.on('click', '.newButton', function(e) {
var button = $(this);
// Handle the individual button click server side call here.
});
});

How to Replace Element In Variable Using jquery And Get Result In Another Variable

I am having a variable with HTML content. Similar to "objHtml" variable below.
I want to replace a div tag with Id = 123 with another new div tag.
var objHtml = "<div> " +
"<div id='123' class='class1'>Text1</div>" +
"<div id='124' class='class1'>Text2</div>" +
"</div>";
// I want to construct this new object using "objHtml", and want to replace div having id = 123 with div having id = 125.
// This Html is in the object and not visible or render on the page.
var newObjHtml = "<div> " +
"<div id='125' class='class1'>Text5</div>" +
"<div id='124' class='class1'>Text2</div>" +
"</div>";
Can any one answer how to replace an element in variable with another element?
$(document).ready(function() {
var objHtml = "<div> " +
"<div id='123' class='class1'>Text1</div>" +
"<div id='124' class='class1'>Text2</div>" +
"</div>";
//Create temporary element
var elem = $(objHtml);
//Find the element and replace it with new HTML
elem.find('#123').replaceWith("<div id='125' class='class1'>Text5</div>");
//Read outerHTML property and update your variable or create new variable
objHtml = elem.prop("outerHTML");
alert(objHtml)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

javascript function using jquery addClass() method does not add class

The script works, creates everything correctly, etc., but the jquery addClass method isn't adding the class. I'm new to using jquery methods in a javascript function, any help is appreciated, including alternate methods for adding the appropriate classes without using jquery.
function thumbnail(Img, Element, Modal, ModalTitle) {
"use strict";
/*jslint browser:true*/
/*global $, jQuery*/
//this function will append an anchor tag with the appropriate functionality, accepting inputs on the image filename, attaching element, and modal
//Img = full filename in format of foo.png
//Element = the ID of the element within which the thumbnail anchor will be placed
//Modal = the ID of the modal
//ModalTitle = Text used for title of the modal and title of the caption
var image, element, modal, loc, output, iUrl, modal_loc, modal_output, mtitle;
image = Img;
element = Element;
modal = Modal;
mtitle = ModalTitle;
iUrl = "/design-library/images/thumbs/" + image;
output = "<a href='#' data-reveal-id='" + modal + "'>";
output += "<img class='sample_img' src='" + iUrl + "' alt='" + mtitle + "' />";
output += "</a>";
output += "<p class='caption'>" + mtitle + "</p>";
modal_output = "<h1>" + mtitle + "</h1>";
modal_output += "<img src='" + iUrl + "' alt='" + image + "' /><a class='close-reveal-modal'>×</a>";
//create the modal container
$(modal).addClass('reveal-modal');
modal_loc = document.getElementById(modal);
modal_loc.innerHTML = modal_output;
//the end of the script gets the element and adds the anchor tag that exists in output
$(element).addClass('samples');
loc = document.getElementById(element);
loc.innerHTML = output;
}
Since modal and element are IDs, you should correct your selectors to use them as ones:
$('#' + modal).addClass('reveal-modal');
$('#' + element).addClass('samples');
Side note. Once you have found the DOM element with jQuery, there is no need to perform the second search with getElementById:
var modal_loc = $('#' + modal);
modal_loc.addClass('reveal-modal');
modal_loc.html(modal_output);
if modal is an ID string, you need to do:
$('#'+modal).addClass('reveal-modal');
Try changing:
$(element).addClass('samples');
to
$('#' + element).addClass('samples');

For Loop to Create DOM element with InnerHTML and Event Handler doesn't work

I've come across a very strange issue that I have a workaround for, but don't actually know why it's happening.
Essentially, I take an existing DOM element, use innerHTML to create append DOM element, and then put in an event handler for it's onclick event.
for(i=0; i<contextMenuModel.length; i++) {
contextMenuRow = contextMenuModel[i];
currentRowId = "edit_context_table_row_" + i;
editTable.innerHTML += "<div id='" + currentRowId + "'></div>";
row = dojo.byId(currentRowId);
row.innerHTML += "<span>" + contextMenuRow.labelName + "</span>";
row.innerHTML += "<span>" + contextMenuRow.eventName + "</span>";
dojo.connect(row, "onclick", row, rowClickHandler);
}
The problem is this: only the last row ends up with the onclick handler. The others do not. It does not matter what browser I'm in, it does not matter if I change dojo.connect to
row.onclick = rowClickHandler;
Also, if I take out the:
row.innerHTML += "<span>" + contextMenuRow.eventName + "</span>";
it still does not work.
However, the workaround that I have found (which makes this all the better) is that this works:
for(i=0; i<contextMenuModel.length; i++) {
contextMenuRow = contextMenuModel[i];
currentRowId = "edit_context_table_row_" + i;
editTable.innerHTML += "<div id='" + currentRowId + "'></div>";
row = dojo.byId(currentRowId);
row.innerHTML += "<span>" + contextMenuRow.labelName + "</span>";
row.innerHTML += "<span>" + contextMenuRow.eventName + "</span>";
}
for(i=0; i<contextMenuModel.length; i++) {
row = dojo.byId("edit_context_table_row_" + i);
dojo.connect(row, "onclick", row, rowClickHandler);
}
Such a strange problem.
I find when creating elements dynamically and attaching events to them I usually come out better using document.createElement. This ensures your element is getting added to the dom and you have an object to work with instead of concatenating strings.
var divRow = document.createElement("DIV");
divRow.id = currentRowId;
divRow.onclick = function(){};
editTable.appendChild(divRow);
So here's the issue. When I do this:
editTable.innerHTML += "<div id='" + currentRowId + "'></div>";
I am concatenating and then replacing the old innerHTML. That means that a new DOM node is generated; this new DOM node is not connected to the old event handler. This leaves the old event handler around, doing nothing. Not to mention that the code is creating and discarding so many DOM nodes, this code is really terrible.

JQuery UnBind Works, Attempt to "re" bind does not

I'm working my way through a JQuery Solution and for the most part it works but I"m stumped on seemingly a small detail I know I'm overlooking. Heck, maybe my implementation/approach needs to be reconsidered.
Here's the flow of what works.
1. Click an anchor that adds to a table.
2. Add CSS Class.
3. Disable (Unbind) click on after preappend().
4. From the table of dynamically added record remove table based on ID.
5. delete class that was added in step 2.
6. Bind 'click'
However, although I can bind the click and alert on it. The expected functionality does not allow me to step through the above process again.
The code in question:
HTML SAMPLE:
link that starts the process:
table that holds new records after click of link
<table id="carrier-table"><tbody></tbody></table>
JQUERY and Custom Javascript Function
<script type="text/javascript" id="removeCarrier">
function removeCarrierFromList(obj) {
var i = obj.parentNode.parentNode.rowIndex;
document.getElementById('carrier-table').deleteRow(i);
$('a#' + obj.id).removeClass('delete-carrier-company');
//alert(obj.id); //.hasClass('add-carrier-company').tostring() ); //
$('a#' + obj.id).bind('click', function() {
//alert('User clicked on ' + obj.id);
});
}
</script>
<script type="text/javascript" id="carrierListJS">
$(function() {
// Link
// This adds a carrier to a list
$('.add-carrier-company').click(
function() {
var target = $(this).attr("id");
alert(target);
$("#carrier-table").prepend("<tr id='carrierRow_" + target + "'>" +
"<td><a href='#' id='" + target + "' class='delete' onclick='removeCarrierFromList(this)'> </a></td>" +
"<td class='carrier-list-text'>" + target + " " + $("#name_" + target).val() + "</td>" +
"</tr>");
return false;
});
$('.add-carrier-company').click(
function() { $(this).addClass('delete-carrier-company').unbind('click'); }
);
});
</script>
There were a few issues I noticed with the code. For one thing, as #RussellUresti mentioned, you create two tags with the same ID. For another thing, if you're using ID's in a selector in jQuery, don't include the tag name, just use the id (ie. use $('#id') not $('a#id')) it will be faster (it won't break your code though).
I have created a jsfiddle to answer your question (though I rewrote most of it). :) I think it's what you're looking for.
Here's the code:
Test HTML
aa
bb
cc
10002
10003
<table id="carrier-table" style="border:1px solid #000"><tbody></tbody></table>
JavaScript
function addCarrier() {
var target = $(this).attr("id");
$("#carrier-table").prepend("<tr id='carrierRow_" + target + "'>" + "<td><a href='#' id='a" + target + "' class='delete'> </a></td>" + "<td class='carrier-list-text'>" + target + " " + $("#name_" + target).val() + "</td>" + "</tr>");
$('#a' + target).click(removeCarrierFromList);
$(this).addClass('delete-carrier-company').unbind('click');
return false;
}
function removeCarrierFromList() {
var $this = $(this);
var id = $this.attr('id').replace("a","");
$this.closest('tr').remove();
$('#' + id).removeClass('delete-carrier-company').click(addCarrier);
}
$(function() {
// Link
// This adds a carrier to a list
$('.add-carrier-company').click(addCarrier);
});

Categories

Resources