jQuery modify value on specific table cell - javascript

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>

Related

iterate through a html table and get row number for each row in javascript

I want to be able to iterate though a html table, get the number of rows, and output the row number of each row on the leftmost field. However, I have 2 problems: not being able to get the number of rows and not getting the desired output.
$(document).ready(function($) {
function create_html_table(tbl_data) {
var tbl = '';
tbl += '<table id ="datarepo">';
tbl += '<thead>';
//Some headers
tbl += '</thead>';
tbl += '<tbody>';
$.each(tbl_data, function(index, val) {
/* This is what I want to use to get the number of rows in the table.
However, uncommenting the following line will cause the whole table to disappear altogether.*/
// var numberrows = document.getElementById("datarepo").rows.length;
// Using static value here instead of numberrows because it is not working.
for (i = 1; i <= 2; i++) {
tbl += '<tr>';
tbl += '<td >' + i + '</td>';
tbl += '<td ><div col_name="filename">' + val['filename'] + '</div></td>';
tbl += '</tr>';
}
});
tbl += '</tbody>';
tbl += '</table>';
}
}
Desired output:
What I got:
You can just get rid of your for loop and use the index of the each loop plus one:
$.each(tbl_data, function(index, val) {
tbl += '<tr>';
tbl += '<td >' + (index + 1) + '</td>';
tbl += '<td ><div col_name="filename">' + val['filename'] + '</div></td>';
tbl += '</tr>';
});

create dynamically table and add image

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>

I can't show my array in JavaScript

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!

creating and appending a button to the end of each row in a dynamic html table using javascript

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*/}

jquery fadeIn effect with <tr>

I am adding rows dynamically to a table based on selection yet I would like to add fadeIn effect.
I am posting the part in which I add the rows to table.
Any help will be appreciated.
(I am trying to use the fadeIn effect while adding newRow to table and removing tblGraphPattern content afterwards). I want to have the effect in the lines
$("table.selectPattern").append(newRow);
$("#tblGraphPattern tr").remove();
var newRow = $("<tr>");
newRow.attr("align","center");
newRow.css("outline", "thin solid");
for(var i = 1; i<counter;++i)
{
if($("#divSubject"+i+"").length>0)
{
var cols = "";
subjectText=$("#divSubject"+i+"").html();
if(subjectText=="Any")
{subjectVal = "?s"+selectCounter;}
else{subjectVal=$("#txtGraphSubject"+i+"").val();}
predicateText=$("#divPredicate"+i+"").html();
if(predicateText=="Any")
{predicateVal = "?p"+selectCounter;}
else{predicateVal=$("#txtGraphPredicate"+i+"").val();}
objectText=$("#divObject"+i+"").html();
if(objectText=="Any"){objectVal="?o"+selectCounter;}
else{
objectVal=$("#txtGraphObject"+i+"").val();
}
cols += '<tr><td align="right"><div id="divSelectSubject'+num+'">'+subjectText+'</div><input type="text" value="'+subjectVal+'" name="txtSelectSubject'
+ num + '" id="txtSelectSubject' + num + '"/></td>';
cols += '<td align="center"><div id="divSelectPredicate'+num+'">'+predicateText+'</div><input type="text" value="'+predicateVal+
'" name="txtSelectPredicate' + num + '" id="txtSelectPredicate' + num + '"/></td>';
cols += '<td align="left"><div id="divSelectObject'+num+'">'+objectText+'</div><input type="text" value="'+objectVal+
'" name="txtSelectObject' + num + '" id="txtSelectObject' + num + '"/></td></tr>';
newRow.append(cols);
}
num++;
}
selectCounter++;
newRow.append('<td><input type="button" class="ibtnDel" value="Delete"></td>');
$("table.selectPattern").append(newRow);
$("#tblGraphPattern tr").remove();
Make your newRow hidden by setting display:none; before appending it to table.selectPattern and then fadeIn after appending is done.
var newRow = $('<tr style="display:none;"></tr>');
// your remaining code
$("table.selectPattern").append(newRow);
$("#tblGraphPattern tr").remove();
newRow.fadeIn(2000);

Categories

Resources