How can you insert a div into another created in javascript - javascript

So I'm trying to insert one div into another both created with Javascript
I have the following code,
// Assign tool attributes to Javascript Variables
var tool_name = String(tool['tool_name']);
tool_name = tool_name.replace(/'/g, '');
var tool_inventory_number = String(tool['tool_inventory_number']);
tool_inventory_number = tool_inventory_number.replace(/'/g, '');
var tool_recnum = String(tool['tool_recnum']);
tool_recnum = tool_recnum.replace(/'/g, '');
// Create the divs for the search results
var toolDiv = document.createElement("div");
var toolDivPicture = document.createElement("div");
//todo: Insert picture into this toolDivPicture div
var toolDivDescription = document.createElement("div");
toolDivDescription = toolDivDescription.innerHTML + "<h2>" + tool_name + "</h3>" + " <br>" + "Inventory Number: " + tool_inventory_number;
// Assign class to search result toolDiv and add content to it.
toolDiv.className = "toolDiv";
toolDiv.appendChild(toolDivDescription);
I keep getting the following error,
Uncaught NotFoundError: Failed to execute 'appendChild' on 'Node': The new child element is null.
Could this be because I have to refrence the child div by id? I really just want to have javascript create a div that contains two other divs and then insert it into the page. Any help/suggestions are appreciated!

Since you marked the question with the jQuery tag, I assume that you have the jQuery library loaded:
// Create the divs for the search results
var toolDiv = $("<div/>");
var toolDivPicture = $("<div/>");
var toolDivDescription = $("<div/>");
toolDivDescription.html("<h2>" + tool_name + "</h3>" + " <br>" + "Inventory Number: " + tool_inventory_number);
// Assign class to search result toolDiv and add content to it.
toolDiv.addClass("toolDiv");
toolDiv.append(toolDivDescription);
Note that you start a h2 but end a h3.
jsFiddle

Try this:
Wrap up your JavaScript in an onload function. So first add:
<body onload="loadJS()">
Then put your javascript in the load function, so:
function loadJS() {
// Assign tool attributes to Javascript Variables
var tool_name = String(tool['tool_name']);
tool_name = tool_name.replace(/'/g, '');
var tool_inventory_number = String(tool['tool_inventory_number']);
tool_inventory_number = tool_inventory_number.replace(/'/g, '');
var tool_recnum = String(tool['tool_recnum']);
tool_recnum = tool_recnum.replace(/'/g, '');
// Create the divs for the search results
var toolDiv = document.createElement("div");
var toolDivPicture = document.createElement("div");
//todo: Insert picture into this toolDivPicture div
var toolDivDescription = document.createElement("div");
toolDivDescription = toolDivDescription.innerHTML + "<h2>" + tool_name + "</h3>" + " <br>" + "Inventory Number: " + tool_inventory_number;
// Assign class to search result toolDiv and add content to it.
toolDiv.className = "toolDiv";
toolDiv.appendChild(toolDivDescription);
}

Related

Issues attempting to display data from JSON file

Premise:
I'm playing around with javascript and have been trying to display a populated JSON file with an array of people on the browser. I've managed to display it through ajax, but now I'm trying to perform the same task with jQuery.
Problem:
The problem is that it keeps saying customerdata[i] is undefined and can't seem to figure out why.
$(function() {
console.log('Ready');
let tbody = $("#customertable tbody");
var customerdata = [];
$.getJSON("MOCK_DATA.json", function(data) {
customerdata.push(data);
});
for (var i = 0; i < 200; i++) {
//Cell for name
let nameTD = $('<td>').text(customerdata[i].first_name + ", " + customerdata[i].last_name);
//Cell for birthdate
let mDate = moment(customerdata[i].birthdate);
let formattedmDate = mDate.format('YYYY-MM-DD');
let birthdateTD = $('<td>').text(formattedmDate);
//Cell for Address
let addressTD = $('<td>').html("City: " + customerdata[i].city + '<br>' + "Email: " + customerdata[i].email + '<br>' + '<a href=' + customerdata[i].website + '>Website</a>');
//Cell for Credits
let creditTD = $('<td>').text(customerdata[i].credits);
let row = $('<tr>').append(nameTD).append(birthdateTD).append(addressTD).append(creditTD);
tbody.append(row);
}
})
SAMPLE CONTENT OF MOCK_DATA.json
[
{"id":1,"first_name":"Tracey","last_name":"Jansson","email":"tjansson0#discuz.net","gender":"Female","ip_address":"167.88.183.95","birthdate":"1999-08-25T17:24:23Z","website":"http://hello.com","city":"Medellín","credits":7471},
{"id":2,"first_name":"Elsa","last_name":"Tubbs","email":"etubbs1#uol.com.br","gender":"Female","ip_address":"61.26.221.132","birthdate":"1999-06-28T17:22:47Z","website":"http://hi.com","city":"At Taḩālif","credits":6514}
]
Firstly, you're pushing an array into an array, meaning you're a level deeper than you want to be when iterating over the data.
Secondly, $.getJSON is an asynchronous task. It's not complete, meaning customerdata isn't populated by the time your jQuery is trying to append the data.
You should wait for getJSON to resolve before you append, by chaining a then to your AJAX call.
$.getJSON("MOCK_DATA.json")
.then(function(customerdata){
for(var i = 0; i < 200; i++){
//Cell for name
let nameTD = $('<td>').text(customerdata[i].first_name + ", " + customerdata[i].last_name);
//Cell for birthdate
let mDate = moment(customerdata[i].birthdate);
let formattedmDate = mDate.format('YYYY-MM-DD');
let birthdateTD = $('<td>').text(formattedmDate);
//Cell for Address
let addressTD = $('<td>').html("City: " +
customerdata[i].city + '<br>' + "Email: " +
customerdata[i].email + '<br>' + '<a
href='+customerdata[i].website+'>Website</a>');
//Cell for Credits
let creditTD = $('<td>').text(customerdata[i].credits);
let row = $('<tr>').append(nameTD).append(birthdateTD).append(addressTD).append(creditTD);
tbody.append(row);
}
})
You also won't need to define customerdata as an empty array at all with this approach.
The problem is that data is already an array.
so you should use:
customerdata = data;
otherwhise you are creating an array in the pos 0 with all the data

How to retrieve function input javascript

I've got the following code that produces a dynamically created image button and panel in asp.net: -
Panel panBlocks = new Panel();
panBlocks.ID = "PanBlockQuestionID" + recordcount.ToString();
panBlocks.Width = 1300;
panBlocks.Height = 50;
panBlocks.BackColor = Color.Pink;
ImageButton cmdBlocks = new ImageButton();
cmdBlocks.ImageUrl = "~/Images/block3.png";
cmdBlocks.ID = "lblImg" + recordcount.ToString();
cmdBlocks.Attributes["class"] = "liQuestionsLabel2";
cmdBlocks.Width = 30;
cmdBlocks.Attributes.Add("OnMouseOver", "showPanel(" + "CPH_Body_" + panBlocks.ClientID.ToString() + ")");
cmdBlocks.Attributes.Add("OnMouseOut", "hidePanel();");
li.Controls.Add(cmdBlocks);
li.Controls.Add(panBlocks);
When I hover over the image I want it to display a particular panel. I've added the "CPH_Body_" + panBlocks.ClientID.ToString() as an attribute.
I've got the following javascript code:
function showPanel(PanelID)
{
document.getElementById("CPH_Body_liQuestions1").style.height = "40px";
}
How do I retrieve the PanelID in the javascript please as it looks like an array. I need to retrieve this so I know which panel to display please.
IIUC (!!):
Change this :
cmdBlocks.Attributes.Add("OnMouseOver", "showPanel(" + "CPH_Body_" + panBlocks.ClientID.ToString() + ")");
To:
cmdBlocks.Attributes.Add("OnMouseOver", "showPanel('" + panBlocks.ClientID.ToString() + "')");
And change this :
function showPanel(PanelID)
{
document.getElementById("CPH_Body_liQuestions1").style.height = "40px";
}
To
function showPanel(PanelID)
{
document.getElementById(PanelID).style.height = "40px";
}

jquery Append add same value always

I use this jQuery code to append a div to another:
$('#sklep').on('click', '.kup', function () {
var cena = $('#cena').text();
var tytul = $('#tytul').text();
var iden = $('#id').text();
var suma = $('#koszykdiv .cyfry').text();
var dodawanie = parseInt(cena) + parseInt(suma);
$('.cyfry').text(dodawanie);
var source = $("#miniatura").attr("src");
$('.koszyk_content_items').append($('<div class="item_koszyk"><div class="miniatura_koszyk"><img width="165" height="110" src="' + source + '"/></div><span id="opis">' + tytul + ' - ' + cena + ' zł - </span><span class="identyfikator" style="display:none;">' + iden + '</span>USUŃ</div>'));
var licznik = $('#koszykdiv .licznik').text();
alert(licznik);
$('#identyfikator').text(licznik);
var licznik_dodawanie = parseInt(licznik) + 1;
$('#koszykdiv .licznik').text(licznik_dodawanie);
$.cookie("obraz" + licznik_dodawanie, id);
var cena = '';
var tytul = '';
var iden = '';
var source = '';
});
but it always appends a div with the same variables values, even if parent of '.kup' href has another text values. Can you help me and tell where the problem is?
You say in your question that you get the same variable values "even if parent of '.kup' href has another text values."
This is because nothing in your code is relative to the '.kup'-element. You get the src-attribute of the element with id=miniatura everytime.

Is it possible to use cloneNode to clone multiple divs?

I'm trying to clone to divs in and append them to to other divs (their parents). I'm using clonenode for this but it doesn't seem to work. It clones the div in the first function and appends it to the parent of the div in the second function! Not sure what I'm doing wrong.
Here's the code (*EDIT:*var added):
function cloneQ() {
//Cloning questions and shit
cloneQ.id = (cloneQ.id || 0) + 1;
var question = document.getElementById("question");
var clone = question.cloneNode(true);
var numberOfQuestions = $('.question').length;
var id = "questioncon" + cloneQ.id;
clone.id = id;
question.parentNode.appendChild(clone);
var inid = "question" + cloneQ.id;
var optionid = "optionsdiv" + cloneQ.id;
$('#' + id + ' ' + '.' + 'questionin').attr('id', inid);
$('#' + id + ' ' + '.' + 'options').attr('id', optionid);
$('#' + id + ' h2').html('Question ' + cloneQ.id);
//Question Cloned
}
function cloneforPrint() {
cloneforPrint.id = (cloneforPrint.id || 0) + 1;
var questionprint = document.getElementById("questionprint");
var cloneprint = questionprint.cloneNode(true);
var printid = "questionprint" + cloneforPrint.id;
cloneprint.id = printid;
questionprint.parentNode.appendChild(clone);
var printinid = "thequestionprint" + cloneforPrint.id;
$('#' + printid + ' ' + '.' + 'thequestionprint').attr('id', printinid);
}
LIVE here: http://bit.ly/R8hB2m
Edit : Global vars are the problem.
You aren't putting var in front of your variables, making them global. The cloneForPrint function is picking up vars defined in cloneQ.
Init all the variables properly and you'll get some errors indicating where the problems are.
CloneQ is indeed appending to questions parent, but cloneForPrint then moves it somewhere else.
-- Old answer --
There's not enough here to work out what the problem is. My 1st guess is that the question element has the same parent as the questionprint element.
Based on the code given, cloneQ should definitely append to questions parent. So to give the appearance you've specified the DOM probably doesn't look like what you expect.

onclick event not firing

var subjectList;
function PageMaster()
{
this.contentDiv = document.getElementById("content");
}
/**
* Builds the main part of the web page based on the given XML document object
*
* #param {Object} xmlDoc the given XML document object
*/
PageMaster.prototype.doIt = function(xmlDoc)
{
alert("PageMaster()");
alert("Clear page...");
this.contentDiv.innerHTML = "";
if (null != xmlDoc)
{
alert("Build page...");
//create div Post
var divPost = document.createElement("div");
divPost.className = "post";
//create h1 element
var h1Element = document.createElement("h1");
var headingText = document.createTextNode("Invitations");
h1Element.appendChild(headingText);
//insert h1 element into div post
divPost.appendChild(h1Element);
subjectList = xmlDoc.getElementsByTagName("subject");
var groupList = xmlDoc.getElementsByTagName("group");
for (var i = 0; i < subjectList.length; i++) //for each subject
{
var divEntry = document.createElement("div");
divEntry.className = "entry";
var subjectNum = subjectList[i].attributes[0].nodeValue;
var subjectName = subjectList[i].attributes[1].nodeValue;
var groupId = groupList[i].attributes[0].nodeValue;
var groupName = groupList[i].attributes[1].nodeValue;
var ownerId = groupList[i].attributes[2].nodeValue;
//set up the invitation table attributes
var table = document.createElement("table");
table.width = 411;
table.border = 3;
table.borderColor = "#990000"
tableRow = table.insertRow(0);
tableCell = tableRow.insertCell(0);
var cellContent = "";
//create invitation message
var invitationMsg = "<p>Subject : " + subjectNum + " - " + subjectName + "</p>";
invitationMsg += "<p>You are invited to join " + groupName + " (groupId : " + groupId + ") by owner Id:" + ownerId + "</p>";
cellContent += invitationMsg;
//create buttons
cellContent += "<input type='button' id='acceptButton" + i + "' value='Accept' onclick='acceptInvitation(i)'>"
cellContent += "<input type='button' id='declineButton" + i + "' value='Decline'>"
tableCell.innerHTML = cellContent;
divEntry.appendChild(table);
var blankSpace = document.createElement("p");
divEntry.appendChild(blankSpace);
divPost.appendChild(divEntry);
}
//insert div post into div content
this.contentDiv.appendChild(divPost);
}
};
function acceptInvitation(i)
{
alert("hello");
//alert(subjectList[i].attributes[0].nodeValue);
}
above is extract of my javascript code. What the code do is to create a table of inviting group from the xml file with accept and decline button. when user press accept, the table will disappear and the table below will move up. For now I am only testing my accept invitation button to see if it works.But
my onclick function in the accept button does not work for some reason I don't understand. the alert in acceptInvitation() is not read. Any help will be appreciated. Thanks
What about:
cellContent += "[...] onclick='acceptInvitation("+i+")'>"
This ensures that i is evaluated with the value of the variable instead of as a literal
Try to call it like this
onclick='acceptInvitation();'
Not like this
onclick='acceptInvitation(i)'
dont know if that's what's causing your problem but your outputting onclick='acceptInvitation(i)' Im guessing you want to output acceptInvitation(value-of-i), that is acceptInvitation(" + i + ")
while perhaps not addressing the central problem,
onclick='acceptInvitation(i)'
in this case i would be undefined.
onclick='acceptInvitation("+i+")'
would solve at least one problem. Also, you're using an unusual mixture of innerHTML and DOM methods. Why not stick to the DOM methods and use attachEvent/AddEventListener?
edit: A list apart has a good article on binding of variables at http://www.alistapart.com/articles/getoutbindingsituations/
The following is a somewhat specialized example. See the article for more generalized case (or use a library like Prototype)
var click_hdlr = function() {
return function() {
return acceptInvitation.apply(this,arguments);
}
}
var acc_btn = document.createElement("input");
acc_btn.setAttribute("type","button");
acc_btn.setAttribute("id","accept");
acc_btn.setAttribute("value","Accept");
acc_btn.addEventListener("click",click_hdlr(i),false);

Categories

Resources