Handle with dynamically made elements in Javascript - javascript

Is there a way to handle elements made dynamically on loading the page?
for example, I have a code below.
function makeAFrame(index)
{
var padding=document.createElement('p');
var frameDiv=document.createElement('div');
frameDiv.id="frame";
frameDiv.className="frame";
var placeButton=document.createElement('input');
placeButton.id="bButton"+index;
placeButton.className="bButton";
placeButton.value="aaa";
placeButton.type="button";
var buyButton=document.createElement('input');
buyButton.id="aButton"+index;
buyButton.className="aButton";
buyButton.value="Buy It Now";
buyButton.type="button";
var table=document.createElement('table');
table.setAttribute('cellpadding','3');
table.setAttribute('width','100%');
var col1=["a", "b", "c","d","e:", "f"];
var row;
var text;
var cell;
var i=0;
for(i=0;i<6;i++)
{
row = table.insertRow(i);
text = document.createTextNode(col1[i]);
cell = row.insertCell(0);
cell.setAttribute('align','right');
cell.setAttribute('width','30%');
cell.appendChild(text);
text = document.createTextNode(hey[index][i]);
cell = row.insertCell(1);
cell.setAttribute('align','left');
cell.appendChild(text);
}
for(i=6;i<8;i++)
{
row = table.insertRow(i);
text = document.createTextNode("");
cell = row.insertCell(0);
cell.setAttribute('align','right');
cell.setAttribute('width','30%');
cell.appendChild(text);
if(i==7)
{
cell = row.insertCell(1);
cell.setAttribute('align','left');
cell.appendChild(placeButton);
cell.appendChild(buyButton);
break;
}
else if(i==6)
text = document.createTextNode(remaining);
cell = row.insertCell(1);
cell.setAttribute('align','left');
cell.appendChild(text);
}
var body=document.getElementById('body');
frameDiv.appendChild(table);
body.appendChild(frameDiv);
body.appendChild(padding);
}
Once the function has been run which means after all elements are shown in the page. What I would like to do is when I click a 'aButton0'(aButton+index) a input box shows up. I make all button codes with index so they are accessible but I have no idea how to access after they are shown in the page.

Why dont you just add an onclick handler to your button when you create it, just add
placeButton.setAttribute("onclick", "showPopUp();");
Then you can react to your specific button within in the showPopUp function.

Related

Jquery adding cell in HTML table i want i set it display none as these are ids ? MVC

I am actually adding id to HTML table than using them for saving.
But i dont want to show it,
here is my jquery for adding cell to the table,
$("body").on("click", "#btnAdd", function () {
//Reference the Name and Country TextBoxes.
var txtName = $("#txtFamilyName");
// var txtCountry = $("#txtCountry");
//Get the reference of the Table's TBODY element.
var tBody = $("#tblCustomers > TBODY")[0];
//Add Row.
var row = tBody.insertRow(-1);
//Add Name cell.
var cell = $(row.insertCell(-1));
cell.html($('#ddlregion').find('option:selected').text());
var cell = $(row.insertCell(-1));
cell.html($('#ddlcityy').find('option:selected').text());
var cell = $(row.insertCell(-1));
cell.html(ddlcityy.value);
var cell = $(row.insertCell(-1));
cell.html(ddltribe.value);
//Add Button cell.
cell = $(row.insertCell(-1));
var btnRemove = $("<input />");
btnRemove.attr("type", "button");
btnRemove.attr("onclick", "Remove(this);");
btnRemove.val("Remove");
cell.append(btnRemove);
});
This jquery adding city and tribe id i want to add them but not to display.
EDITED:
cell.setAttribute("hidden", true); or ` cell.style.display = 'none';
They both are working but only for one cell
let see i change to
var cell = $(row.insertCell(-1));
cell.html(ddlcityy.value);
cell.setAttribute("hidden", true);
var cell = $(row.insertCell(-1));
cell.html(ddltribe.value);
cell.setAttribute("hidden", true);
"Cityid" is 3 and "Tribeid" is 1 its every time hiding only tribe id not city id.
I even change variable name for both of them from cell to cell1 but result is same.
why it is only hiding tribe id ?

Getting value from cell within dynamically generated table

I have a table that is dynamically generated via JavaScript based on data from an SQL query. The first cell contains a button that should retrieve the value in the 2nd cell within that row onclick. For some reason, the jQuery onclick event is not firing. No errors are being thrown in the browser.
HTML
...
for (var i=0; i<queryReturned.Result.length; i++) {
var tableRow = document.createElement("tr");
var cell = document.createElement("td");
var button = document.createElement("button"); //Button gets added here
button.type = "button";
button.value = "Remove Alert";
button.className = "buttonSelect"
cell.appendChild(button);
tableRow.appendChild(cell);
//This loop creates the rest of the cells and fills in their data
for (var j=0; j<Object.keys(queryReturned.Result[i]).length; j++) {
var cell2 = document.createElement("td");
var cellText = document.createTextNode(Object.values(queryReturned.Result[i])[j]);
cell2.appendChild(cellText);
tableRow.appendChild(cell2);
}
tableBody.appendChild(tableRow);
}
table.appendChild(tableBody);
table.setAttribute("border", "2");
body.appendChild(table);
...
jQuery
$(document).ready(function(){
$(".buttonSelect").on('click',function(){
var currentRow=$(this).closest("tr");
var col2=currentRow.find("td:eq(1)").html();
alert(col2); //alert for now to test if we grabbed the data
});
});
Reword your event handler function like so:
$(document).on('click', '.buttonSelect', function(){ ... });
so it will work for dynamically added elements as well.
Let us know how it goes!
Firstly the main problem is that you need to use a delegated event handler to attach the click event to the button element.
Also, you're using an odd mix of JS and jQuery. You can massively simplify the table creation logic. Too. Try this:
$(function() {
var $table = $('<table />').appendTo('body'); // this wasn't in your code example, but should look like this
queryReturned.Result.forEach(function(result) {
var $tr = $("<tr />").appendTo($table);
var $td = $("<td />").appendTo($tr);
$('<button class="buttonSelect">Remove Alert</button>').appendTo($td);
for (var j = 0; j < Object.keys(result).length; j++) {
$('<td />').text(result[j]).appendTo($tr);
}
}
$(document).on('click', '.buttonSelect', function() {
var currentRow = $(this).closest("tr");
var col2 = currentRow.find("td:eq(1)").html();
alert(col2);
});
});

Insert cells in specific column in Table

I have a Table with 3 thead.
I'm trying to insert cells in the second column.
I put the insertCell function as follows:
cell = row.insertCell(2);
but it doesn't work.
This is my code :
function add() {
j++;
count++;
var table = document.getElementById('table0');
var row = table.insertRow(-1);
cell = row.insertCell(1);
text = count;
cell.appendChild(document.createTextNode(text));
}
Here is my JSFiddle code
Can anyone help me?
The index you pass to row.insertCell(index) must be less than or equal to row.cells.length. In your case, since row is a brand new row, row.cells.length is 0, so you must pass 0 or -1.
Consider the HTML for your table. How would you write the HTML for a row containing a single cell, in the 2nd column? You can't do it! If there is a cell in the second column, there must also be a cell in the first column.
To create a new row in table, with a cell in the second column:
var row = table.insertRow(-1);
var firstCell = row.insertCell(-1);
var secondCell = row.insertCell(-1);
To give it the appearance of having no cell in the first column, use CSS to git rid of the border and any other styles that make it look like a cell:
firstCell.className = "empty";
.empty {
border: 0 none;
}
http://jsfiddle.net/54pmo8oy/14/
I'm not clear whether this is what you're trying to do, but hopefully it's close. Clicking the button will add a new cell to the second column with each click:
(function () {
var count = 1,
add = function () {
var table = document.getElementById('table0'),
row = table.rows[0],
cell = row.insertCell(1),
text = count;
cell.innerHTML = text;
count++;
};
document.getElementsByTagName('button')[0].addEventListener('click', function () {
add();
});
add();
}());
JSFiddle

How can I reference an element after I have appended it using javascript not jquery

I am doing some basic javascripting and am creating a 3 column table created by javascript sourced from an xml. The table is created by appending all the data in rows via javascript.
The first column has an input checkbox, created via javascript, that if ticked fetches a price from the third column on that row and adds all the prices of the rows selected to give a price total.
The problem I am having is I don't seem to be able to reference the appended information to obtain the information in the related price column (third column).
I have attached both the function I am using to create the table which is working and the function I am using to try and add it up which isnt working.
I found the following two articles Getting access to a jquery element that was just appended to the DOM and How do I refer to an appended item in jQuery? but I am using only javascript not jquery and would like a javascript only solution if possible.
Can you help? - its just the calculateBill function that isn't working as expected.
Thank you in advance
function addSection() {
var section = xmlDoc.getElementsByTagName("section");
for (i=0; i < section.length; i++) {
var sectionName = section[i].getAttribute("name");
var td = document.createElement("td");
td.setAttribute("colspan", "3");
td.setAttribute("class","level");
td.appendChild(document.createTextNode(sectionName));
var tr = document.createElement("tr");
tr.appendChild(td);
tbody.appendChild(tr);
var server = section.item(i).getElementsByTagName("server");
for (j=0; j < server.length; j++) {
var createTR = document.createElement("tr");
var createTD = document.createElement("td");
var createInput = document.createElement("input");
createInput.setAttribute("type", "checkbox");
createInput.setAttribute("id", "checkInput");
createTD.appendChild(createInput);
createTR.appendChild(createTD);
var item = server[j].getElementsByTagName("item")[0].innerHTML;
var createTD2 = document.createElement("td");
var createText = document.createTextNode(item);
createTD2.appendChild(createText);
createTR.appendChild(createTD2);
var price = server[j].getElementsByTagName("price")[0].innerHTML;
var createTD3 = document.createElement("td");
var createText2 = document.createTextNode("£" + price);
createTD3.appendChild(createText2);
createTR.appendChild(createTD3);
tbody.appendChild(createTR);
}
}
}
onload = addSection();
function calculateBill() {
var finalBill = 0.0;
var checkBox = document.getElementById("checkInput");
for (i=0; i < checkBox.length; i++) {
if (checkBox[i].checked) {
var parentTR = checkBox[i].parentNode;
var priceTD = parentTR.getElementsByTagName('td')[2];
finalBill += parseFloat(priceTD.firstChild.data);
}
}
return Math.round(finalBill*100.0)/100.0;
}
var button = document.getElementById("button");
button.onClick=document.forms[0].textTotal.value=calculateBill();
When you do x.appendChild(y), y is the DOM node that you are appending. You can reference it via javascript either before or after appending it. You don't have to find it again if you just hang on to the DOM reference.
So, in this piece of code:
var createInput = document.createElement("input");
createInput.setAttribute("type", "checkbox");
createInput.setAttribute("id", "checkInput");
createTD.appendChild(createInput);
createInput is the input element. You can reference it with javascript at any time, either before or after you've inserted it in the DOM.
In this piece of code:
var price = server[j].getElementsByTagName("price")[0].innerHTML;
var createTD3 = document.createElement("td");
var createText2 = document.createTextNode("£" + price);
createTD3.appendChild(createText2);
createTR.appendChild(createTD3);
tbody.appendChild(createTR);
You're creating a <td> element and putting a price into it. createTD3 is that particular <td> element.
If you want to be able to find that element sometime in the future long after the block of code has run, then I'd suggest you give it an identifying id or class name such that you can use some sort of DOM query to find it again. For example, you could put a class name on it "price" and then be able to find it again later:
var price = server[j].getElementsByTagName("price")[0].innerHTML;
var createTD3 = document.createElement("td");
createTD3.className = "price";
var createText2 = document.createTextNode("£" + price);
createTD3.appendChild(createText2);
createTR.appendChild(createTD3);
tbody.appendChild(createTR);
Then, you could find all the price elements again with:
tbody.querySelectorAll(".price");
Assuming tbody is the table where you put all these elements (since that's what you're using in your enclosed code). If the table itself had an id on it like id="mainData", then you could simply use
document.querySelectorAll("#mainData .price")
to get all the price elements.
FYI, here's a handy function that goes up the DOM tree starting from any node and finds the first node that is of a particular tag type:
function findParent(node, tag) {
tag = tag.upperCase();
while (node && node.tagName !== tag) {
node = node.parentNode;
}
return node;
}
// example usage:
var row, priceElement, price;
var checkboxes = document.querySelectorAll(".checkInput");
for (var i = 0; i < checkboxes.length; i++) {
// go up to the parent chain to find out row
row = findParent(checkboxes[i], "tr");
// look in this row for the price
priceElement = row.querySelectorAll(".price")[0];
// parse the price out of the price element
price = parseFloat(priceElement.innerHTML.replace(/^[^\d\.]+/, ""));
// do something here with the price
}

Align cell javascript

i'm using javascript to add rows to a table dynamically:
function addRow() {
var table = document.getElementById("bestelling");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount-5);
var cell1 = row.insertCell(0);
var bedrag = document.createElement("input");
bedrag.type = "text";
bedrag.name = "bedrag[]";
cell1.appendChild(bedrag);
}
This seems to work perfectly, except I want the first cell to align right.
Any suggestions?
You can try adding this (I am assuming that cell1 is the "first cell" that you are referring to):
cell1.style.textAlign = "right";
This styles the cell with CSS textAlign right.
Alternatively, you can set a class name to the cell with this JavaScript code:
cell1.className = "alignRight"
And use CSS to set the align right.
.alignRight{
text-align:right;
}
To make this even simpler, you could use jQuery - http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
$("<tr id='new-row'>").insertBefore("#first-row") // # is the id selector
Then you can set the style and content of #new-row using the html() and css() methods:
$("#new-row").css("text-align","right");
$("#new-row").html("Hello world!");
Hope this helps.

Categories