I'm trying to create a table of 3 cards like X X X
I cant add any rows or columns
all need to be dynamically so the body is empty:
<script>
var $card = $('<div />').appendTo('body');
var $table = document.createElement("table");
var $image = document.createElement("IMG");
$('#table').find('body').append("<tr>");
$('#table').find('body').append("<td>" + $image.src + "</td>");
$('#table').find('body').append("<td>" + $image.src + "</td>");
$('#table').find('body').append("<td>" + $image.src + "</td>");
$('#card').html($table);
$card.append($table);
for (var i = 0; i < 3; i++) {
$image.src = "/images/ACE.jpg";
$('#card').html($image);
$card.append($image);
}
</script>
If you are going to generate elements in the DOM, you have to append them to the element that they are expected to be children of. This is a basic example of creating elements and appending them to their parent. This should hopefully give you an idea of how your logic could work.
var $body = $(document.body);
//make a table
var $table = $('<table>');
//make a row
var $row = $('<tr>');
//make a column
var $col = $('<td>');
//put something in the column
$col.append('Hey there!');
//put the column in the row
$row.append($col);
//put the row in the table
$table.append($row);
//put the table in the body
$body.append($table);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Or you could build the markup first as a string before you ever append it.
var $body = $(document.body);
var html = '';
//make a table
html += '<table>';
//make a row
html += '<tr>';
//make a column
html += '<td>';
//put something in the column
html += 'Hey there!';
//close the column
html += '</td>';
//close the row
html += '</tr>';
//close the table
html += '</table>';
//put the table in the body
$body.append(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You're creating invalid HTML. Also you're mixing incomplete JavaScript code with jQuery. Add a table to the body, then add a tr row to the table, then add three td cells to the row. Your images should go into the cells. Here is a simple code to do so:
var img = '<img src="/images/ACE.jpg" />';
var table = $('<table id="table1"></table>').appendTo('body');
table.append("<tr></tr>");
table.find('tr').append("<td>" + img + "</td>"
+ "<td>" + img + "</td>"
+ "<td>" + img + "</td>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Related
I am creating dynamic table which I has 3 columns. First columns has campaign name 2nd & 3rd column is status of that campaign which is image button. What I expect when I click status button it should return respective campaign name. Nothing happens when I click on status button.
would be great if you can provide solution.
function displayCampaigns(campaignNames) {
var html = "<table class='table table - responsive - md' id='campaignTable'>";
for (var i = 0; i < campaignNames.length; i++) {
html += "<tr>";
html += "<td>" + campaignNames[i] + "</td>";
html += "<td><input type='button' id='telStatus' class='btn btn-success btn-circle btn-sm' onclick=function(){getRow(this)}/></td>";
html += "<td><img src='ready.jpg' id='readyStatus' /></td>";
html += "</tr>";
}
html += "</table>";
document.getElementById("demo").innerHTML = html;
function getRow(obj) {
var txt;
e.preventDefault();
txt = $(this).parent().prev().prev().text();
alert(txt + 'selected txt');
}
i have fixed your problem.
function displayCampaigns(campaignNames) {
var html = "<table class='table table - responsive - md' id='campaignTable'>";
for (var i = 0; i < campaignNames.length; i++) {
html += "<tr>";
html += "<td class='parent'>" + campaignNames[i] + "</td>";
html += "<td><input type='button' id='telStatus' class='btn btn-success btn-circle btn-sm' onclick=getRow(this) /></td>";
html += "<td><img src='ready.jpg' id='readyStatus' /></td>";
html += "</tr>";
}
html += "</table>";
document.getElementById("demo").innerHTML = html;
}
function getRow(event) {
var txt = $(event).parent().prev().text();;
alert(txt + ' selected txt');
}
var a = ["test","test2"];
displayCampaigns(a);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="demo"></div>
You could save the #demo object in a variable and attach an event listener to that. On click check if the event target has a class that you attach to your buttons, like telStatus (don't use that as id because having more than one row will result in several html elements having the same id). Add the campaign name as id or a data attribute to the table rows and just check the clicked buttons parentNodes to retrieve the id/data attribue.
var campaignNames = [
'abc', 'efg'
]
var demo = document.querySelector('#demo');
displayCampaigns(campaignNames);
function displayCampaigns(campaignNames) {
var html = "<table class='table table-responsive-md' id='campaignTable'>";
for (var i = 0; i < campaignNames.length; i++) {
html += "<tr id='" + campaignNames[i] +"'>";
html += "<td>" + campaignNames[i] + "</td>";
html += "<td><input type='button' class='telStatus btn btn-success btn-circle btn-sm'/></td>";
html += "<td><img src='ready.jpg' /></td>";
html += "</tr>";
}
html += "</table>";
demo.innerHTML = html;
}
demo.addEventListener('click', function (evt) {
if (!evt.target.classList.contains('telStatus')) return;
var parentTr = evt.target.parentNode.parentNode;
var campaignName = parentTr.id;
alert(campaignName + ' selected txt');
});
I am trying to programmatically modify a cell content.
this is how I am adding rows to my table:
addLine(id) {
var newRow = $('<tr id=' + this.id + '>');
var cols = "";
cols += '<td>' + name + '</td>';
cols += '<td id=s>test</td>';
newRow.append(cols);
$(".table").append(newRow);
this.id++;
}
and this is how I tried to modify the cell on row 0 with id equl to s
//$(".table").find('tr#'+0).find('td:eq(1)').html("some other text");
This is not changin the content of the second td cell and I am not able to figure out why.
Here's a working sample you just need to call .find('#' + id) to find the wanted row
var id = 0;
var name = "abcdef";
function addLine() {
var newRow = $('<tr id=' + id++ + '>');
var cols = "";
cols += '<td>' + name + '</td>';
cols += '<td id=s>test</td>';
newRow.append(cols);
$(".table").append(newRow);
}
function changeValue() {
$(".table").find('#' + 1).find('td:eq(1)').html("some other text");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<button onclick="addLine()">Add line </button>
<button onclick="changeValue()">Change Value </button>
<table class="table"></table>
The selector for the 2nd td, you should do td:nth-child(2) to select the 2nd one.
Also, a quick note. <table> automatically adds a <tbody> tag under it, so you should really do $('.table tbody').append(newRow).
I fixed some stuff for you:
addLine(id){
var newRow = "<tr id="+id+">";
var cols = "";
cols += '<td>' + name + '</td>';
cols += '<td>test</td>'; // you are always setting the same id. just leave it blank
newRow.append(cols);
newRow = "</tr>"; // tr tag needs to be closed
$(".table").append(newRow);
id++;
}
And the query would be:
$('#'+searchId).children('td').eq(1).html("some other text"); //searchId = id of your row
First of all html ids and classes should not begin with numbers. Using jQuery you can do it without assigning ids to rows and columns.
Also note if your adding Ids make sure all ids are unique.
var id = 1;
function addLine() {
var name = "Row " + id + " column 1";
var newRow = $('<tr>');
var cols = "";
cols += '<td>' + name + '</td>';
cols += '<td>test</td>';
newRow.append(cols);
$(".table").append(newRow);
id++;
}
function changeCell(row, col) {
$(".table").find('tr').eq(--row).find('td').eq(--col).html("some other text");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<button onclick="addLine()">Add Line</button>
<!-- add two rows to change row 2 col 1 value -->
<button onclick="changeCell(2,1)">Change row 2 col 1</button>
<table class="table"></table>
I want to add a td which contains image data which I will add when I calling a function. The function I am returning td with image data, I get blank row only.
var html = "";
html += "<td>" + country + "</td>";
html += "<td>" + gender + "</td>";
html += "<td>" + meal + "</td>";
html+= load_image(img);
html += "<td>" + doc + "</td>";
document.getElementById("data").innerHTML += html;
function
function load_image(ref)
{
var array = ref.split(',');
var html = "";
return "<td>";
for (var i = 0; i < array.length; i++) {
var src = "uploads/"+ array[i];
var img1 = '<img src='+ src +' height="42" width="42">';
return img1
}
html += "</td>";
return html;
}
Use appendChild instead of innerHTML.
Here is a sample:
function load_image(image_src, parentElement){
//image_src is your image's path
//parentElement is your <td> which you want to put an image into it
var newImage = document.createElement('img');
newImage.src = image_src;
newImage.style.width = "300px";
newImage.style.height = "300px";
parentElement.appendChild(newImage);
}
var elem = document.getElementById("data"); //This your parent element, i.e. <td>
load_image("some_image.jpg", elem);
I have some simple code in JavaScript. I was going to create code to add first name, last name and age of students from the client by click on "Add Student" button, and show the list of students including the one just added by clicking on the "Show Students" button.
The add action is successful, but when I click on "Show Students" button it just shows me a table without any information(First Name,Last Name,Age).
var students = new Array();
var i = 0;
function AddStudent()
{
var patt = /i[a-z]/;
var Fname = prompt("enter first name");
var Lname = prompt("enter last name");
var Age = prompt("enter age");
var std= {fname : Fname,lname : Lname,age : Age }
students[i++] =std;
}
function ShowStudents()
{
var table = "<table style='background-color:greenyellow; border:solid;'>";
table += "<tr><th>نام</th><th>نام خانوادگی</th><th>سن</th></tr>"
for( var j=0;j<students.length;j++)
{
table += "<tr>"
table += "<td>" + students[j].fname +"</td>"
table += "<td>" + students[j].lname + "</td>"
table += "<td>" + students[j].age + "</td>"
table +="</tr>"
}
table += "</table>";
document.getElementById("ShowStudents").innerHTML = table;
}
<input type="button" value="Add Student" onclick="AddStudent();"/>
<input type="button" value="Show Students" onclick="ShowStudents();"/>
<div id="ShowStudents"></div>
I think that your browser can not execute instructions without " ; " , so try to add it in this lines :
table += "<tr><th>نام</th><th>نام خانوادگی</th><th>سن</th></tr>"
for( var j=0;j<students.length;j++)
{
table += "<tr>"
table += "<td>" + students[j].fname +"</td>"
table += "<td>" + students[j].lname + "</td>"
table += "<td>" + students[j].age + "</td>"
table +="</tr>"
}
because for me it works like a charm.
i had some comment in my js page and useless functions.finally i clean the comment and useless functions and it worked!
I have a table that I have dynamically created from a JSON object I am getting from the server via an ajax request. I am trying to append buttons to the end of each of the rows in the table. The table has seven rows, thus I have 7 buttons. I want something like the following. I want to set a javascript variable to create each individual button with the following parameters :
(obviously with different ids)
<input type="button"id="submit-button2"class="btn btn primary"value="Submit" />
so that I can set up an array of buttons of these variables in javascript such as the following:
var buttons = [
button1,
button2,
button3,
button4,
button5,
button6,
button7
];
Then I can iterate through my JSON object and the buttons array appending them to the table (named requestTable) like the following :
for(var j = 0; j < request[0].DepartmentApprovals.length && buttons.length; j++) {
$("<tr>" + "<td id=\"Departments\">"
+ request[0].DepartmentApprovals[j].Department +":" + "</td>"
+ "<td input type=\"text\" id=\"ApproverLanId\" contenteditable=\"false\" class=\"underline\">"
+ request[0].DepartmentApprovals[j].Approver.LanId + "</td>"
+ "<td>" + "Date:" + "</td>"
+ "<td contenteditable=\"false\" class=\"underline\">" + request[0].DateApproved + "</td>"
+ "<td>" + buttons[j].outerHTML + "</td>"+ "</tr>").appendTo("#requestTable");
}
The table data works, My issue has been that I am able to get a button to append and show if I use the document.getElementById of an existing button already created elsewhere on the form, but clearly I do not want this, I want them dynamically created with differing ids that exist only in the scope of the table. I am not sure how to accomplish this through javascript.
I am not 100% sure if this is what you want, but this code should add a button with a dynamic ID (submit-button-1, submit-button-2, etc ...) inside the last cell of each row:
for (var j = 0; j < request[0].DepartmentApprovals.length && buttons.length; j++) {
var appendHTML = '';
appendHTML += '<tr>';
appendHTML += '<td id="Departments">' + request[0].DepartmentApprovals[j].Department + ':</td>';
appendHTML += '<td input type="text" id="ApproverLanId" contenteditable="false" class="underline">' + request[0].DepartmentApprovals[j].Approver.LanId + '</td>';
appendHTML += '<td>Date:</td>';
appendHTML += '<td contenteditable="false" class="underline">' + request[0].DateApproved + '</td>';
appendHTML += '<td><input type="button" id="submit-button-' + (j + 1) + '" class="btn btn primary" value="Submit" /></td>';
appendHTML += '</tr>';
appendHTML.appendTo('#requestTable');
}
try this
var button = document.createElement("button");
button.innerHTML ="/*put name of button here*/";
// 2. Append somewhere
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
// 3. Add event handler
button.addEventListener ("click", function(){/*put what button does here*/}