Accessing Table in Partial View - javascript

I'm trying to edit a table by adding rows, but running into an issue with the the partial view not being fully rendered (This is my assumption)
I'm loading the partials into their divs via page load and ajax calls;
<div id="preTestSteps">
</div>
<div id="mainTestSteps">
</div>
<div id="postTestSteps">
</div>
Scripts;
$(document).ready(function() {
var testSuiteExecutionId = #(Model.TestSuiteExecutionId);
var testSuiteId = #(Model.TestSuiteId);
loadTestStepResultsPartialView(testSuiteExecutionId, testSuiteId, 1, "preTestSteps");
loadTestStepResultsPartialView(testSuiteExecutionId, testSuiteId, 0, "mainTestSteps");
loadTestStepResultsPartialView(testSuiteExecutionId, testSuiteId, 2, "postTestSteps");
});
function loadTestStepResultsPartialView( testSuiteExecutionId, testSuiteId, testStepType, divId) {
$.ajax({
type: 'POST',
url: '#Url.Action("DetailsTestStepResults", "TestSuiteExecutions")',
data: { 'testSuiteExecutionId': testSuiteExecutionId, 'testSuiteId': testSuiteId, 'testStepType': testStepType },
success: function(data) {
$("#" + divId).html(data);
}
});
In the partial view, the table has a unique ID which is accessed to append (view model is a list of viewmodels, using the first index is to get data which is unique for the list of logs);
<div id="#collapseStepItemName" class="collapse col-sm-12" role="tabpanel" aria-labelledby="headingOne">
<div class="card-body">
<table class="table" id="logTable_#Model[0].TestStepId#Model[0].MessageType">
<thead>
<tr>
<th width="5%"></th>
<th width="20% !important">Time</th>
<th width="75%">Message</th>
</tr>
</thead>
<tbody>
#foreach (var logEntry in Model)
{
<tr id="tableRow_#logEntry.TestStepId#logEntry.MessageType">
<td><img width="20" height="20" src="~/Content/Images/#HtmlUtilities.GetTestSuiteExecutionIconName(logEntry.LogType)" /></td>
<td><i>#logEntry.TimeStamp</i></td>
<td><i>#Html.Raw(HtmlUtilities.GetHtmlFormattedString(logEntry.Message))</i></td>
</tr>
}
</tbody>
</table>
</div>
The current test code (with hard coded tableID for the sake of testing) is the following;
var tableId = "logTable_" + 44 + "False";
var newRow = document.getElementById(tableId).insertRow();
newRow.innerHTML="<td>New row text</td><td>New row 2nd cell</td><td>Please work</td>";
The following error is thrown in the browser debug;
Uncaught TypeError: Cannot read property 'insertRow' of null
Is there a way to execute the script after the partial views are fully rendered? Or is this issue something else and not due to the views being loaded in?
I made sure the table appending script actually works by testing it on a table in the main view, and it worked as intended.

Since you're using jQuery, place this code inside document.ready function:
$(document).ready(function() {
// other stuff
var tableId = "logTable_" + #Model[0].TestStepId + #Model[0].MessageType;
var row = $('<tr>').append('<td>New row text</td><td>New row 2nd cell</td><td>Please work</td>');
$('#' + tableId).find('tbody').append(row);
});
If you insist using vanilla JS to add rows, make sure that all DOM objects are already loaded as given in example below:
document.addEventListener("DOMContentLoaded", function (ev) {
var tableId = "logTable_" + #Model[0].TestStepId + #Model[0].MessageType;
var newRow = document.getElementById(tableId).insertRow();
newRow.innerHTML="<td>New row text</td><td>New row 2nd cell</td><td>Please work</td>";
}
The reason behind insertRow has null value is that table DOM elements may not fully loaded when adding row script executes, hence row addition script should run when all required DOM elements are complete.
Demo example: JSFiddle

Related

Onclick event open a new page and load an table by doing an api call using javascript

I'm trying to display a table on a new page by calling an API and loading the data in the table. This page is loaded on click of a menuItem.
But the issue I'm facing is that the table is displaying, but not the data I'm intending to. I know that I'm able to fetch the data from the API since i can see that in the console log.
Here is the code:
In this first html file im clickling the menu and calling my next html page i want to load
and also im giving my id="covidLink" which im calling in my JS FILE.
pan.html
<div class="navbar">
<a class="covidText" id="covidLink" href="covidStatusUpdate.html">Covid-19</a>
</div>
In the below js file im making a call to the api and appending the data in tbody.
Fetchdata.js
$(document).ready(function () {
$("#covidLink").click(function () {
console.log("Link clicked...");
requestVirusData();
});
});
function requestVirusData() {
$.getJSON('https://api.covid19api.com/summary',
function(data){
var countries_list = data.Countries;
//console.log(countries_list);
$(countries_list).each(function(i, country_dtls){
$('#totalbody').append($("<tr>")
.append($("<td>").append(country_dtls.country))
.append($("<td>").append(country_dtls.TotalConfirmed))
.append($("<td>").append(country_dtls.TotalDeaths))
.append($("<td>").append(country_dtls.TotalRecovered)));
});
})
}
and lastly
statusUpdate.html
<table class="table table-striped table-bordered table-sm" cellspacing="0" width=80%>
<thead>
<tr>
<th>Country</th>
<th>TotalConfirmed</th>
<th>TotalDeaths</th>
<th>TotalRecovered</th>
</tr>
</thead>
<tbody id="totalbody">
</tbody>
</table>
What am I supposed to do ? I have to admit that I'm lost here.
I don't think you quite understand how AJAX works. You're handling a click on "covidLink". This does two things simultaneously.
it tells the browser to navigate away from the current page and go to statusUpdate.html instead.
it runs the requestVirusData() function. This gets the data from the API and returns it to the page.
But the problem is: the API call returns the data to the page where the script was called from - i.e. it returns it to pan.html. And you've just told the browser to move away from that page. Also, pan.html doesn't contain a table to put the returned data into.
The logical solution here is to link to fetchdata.js from statusUpdate.html instead, and tweak the code slightly so it runs when that page loads, rather than on the click of a button:
$(document).ready(function () {
console.log("page loaded...");
requestVirusData();
});
As suggested by ADyson i did changes in my code and now im able to display the table with data.
Here are my code changes:
statusUpdate.html
<tbody id="tbody">
<script>
var datatable;
fetch('https://api.covid19api.com/summary')
.then(function (response) {
return response.json();
})
.then(function (data) {
appendData(data);
})
.catch(function (err) {
console.log('error: ' + err);
});
function appendData(data) {
var countries_list = data.Countries;
var tbody = document.getElementById("tbody");
// clear the table for updating
$('table tbody').empty();
// hide the table for hidden initialize
$('table').hide();
// loop over every country
for (var i in countries_list) {
var country_dtls = countries_list[i];
// replace -1 with unknown
for (var o in country_dtls) {
if (country_dtls[o] == -1) country_dtls[o] = 'Unknown';
}
$('table tbody').append(`
<tr>
<td>${country_dtls.Country}</td>
<td>${country_dtls.TotalConfirmed}</td>
<td>${country_dtls.TotalDeaths}</td>
<td>${country_dtls.TotalRecovered}</td>
</tr>`);
}
}
// }
</script>
</tbody>
pan.html
<a class="covid" href="statusUpdate.html">Covid-19</a>
and now i do not need fetchdata.js obviously.
Hope this helps someone stuck like me :)

Return row's rowIndex on page load

I'm trying to print to page the rowIndex for each row in a table. I would like it to be placed inside the table itself, but I can't seem to get it to work:
<table>
<tr>
<td>r1.cell1</td>
<td>r1.cell2</td>
<td><script>document.write("rowindex = " + this.parentNode.rowIndex);</script></td>
</tr>
<tr>
<td>r2.cell1</td>
<td>r2.cell2</td>
<td><script>document.write("rowindex = " + this.parentNode.rowIndex);</script></td>
</tr>
</table>
Using jQuery is a simple matter of doing it after the document is loaded. Assuming this is the only table in the whole page you could do something like
$('td:last-child').each(function(index, item) { $(item).html(index)})
You can see it in action using this JSFiddle http://jsfiddle.net/qurm4304/

Add a <tr> element to dynamic table, dynamically without a page refresh, php jquery

I am trying to add a dynamic row to the existing table on click of button, whose rows are dynamically created using output from PHP script.
I doing an ajax call to the script insert_tr.php which returns me a TR element in the same format as the existing table with the data.Data is returned appropriately
But unfortunately, the <tr> row is not being added to the table dynamically but adds only after a page refresh.
PHP file code :
<div id="v_div">
<table class="table table-bordered table-striped" >
<thead>
<th class='col-md-2'>name</th>
<th class='col-md-2'>number</th>
</thead>
<tbody>
<?php
while ($data = pg_fetch_assoc($ret)) {
echo
"<tr id=tr_".$data['sr_number'].">
<td class='td_topic' id=title:".$data['number']." >".trim($data['name'])."</td>
<td class='td_topic' id=title:".$data['number']." >".trim($data['number'])."</td>
<td class='td_topic' id=title:".$data['number']." ><button class='btn btn-info check1' type=button title='Add Entry'>Add Entry</button></td>
</tr>";
?>
</tbody>
</table>
</div>
Javascript :
$(document).ready(function() {
$("#v_div").on('click', '.check1', function() {
var field_userid = $(this).parent().attr("id");
var value = $(this).text();
$.post('insert_tr.php', field_userid + "=" + value, function(data) {
if (data != '') {
$(this).closest("tr").after(data);
}
});
});
});
All I want to do is add the row immediately after the current TR am on ,dynamically without a page refresh, which serves the ultimate use of an ajax call.
The reference to this is not the button that was clicked.
$(this).closest("tr").after(data);
Store a reference to the row outside the Ajax call.
$(document).ready(function() {
$("#v_div").on('click', '.check1', function() {
var field_userid = $(this).parent().attr("id");
var value = $(this).text();
var row = $(this).closest("tr");
$.post('insert_tr.php', field_userid + "=" + value, function(data) {
if (data != '') {
row.after(data);
}
});
});
});

How to fetch data from file using ajax on clicking table rows

I am trying to fetch the data from files using Ajax by clicking row of table (passing row values to button on clicking rows) or by entering the variables in text box and pressing button. But it does not seem to be working.(Pls don't downvote as i am C++ programmer and learning web development.)
<!DOCTYPE html>
<html>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"> </script>
<table bodrder=1 class='list'>
<thead>
<tr>
<th class='A'>ID</th>
<th class='B'>Value</th>
<th class='C'>Name</th>
<th class='D'>Cell #</th>
<th class='E'>Nickname</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>54235</td>
<td>Benjamin Lloyd</td>
<td>(801) 123-456</td>
<td>Ben</td>
</tr>
<tr>
<td>2</td>
<td>44235</td>
<td>XXXXXX</td>
<td>642363673</td>
<td>TRE</td>
</tr>
</tbody>
</table>
<div id="tabs" class="plots-tabs" style="padding-top: 10px; padding-bottom: 10px">
<table>
<tr><td>ID:<input id="id" type="text" class="inputbox" /></td></tr>
<tr><td>Value:<input id="value" type="text" class="inputbox" /></td></tr>
</table>
This is DIV element which will be filled by div element on clicking button or by clicking table row which also generate the event and click the button by passing values to ajax and fetchign data.
<p style="width: 100%; text-align: right;"><button type="button" id="button">Submit</button></p>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
//here ID and value are parsed through table click event or from text box on clicking button
$.ajax({
url:filename,
data: {
ID: $("input#id").val(),
Value: $("input#value").val()
},
success:function(result){
$("#tabs").html(result);
}});
var filename= "Data_"+ID+"_"+Value+".txt";
$("#tabs").load(filename);
});
});
var table = document.getElementsByTagName("table")[0];
var tbody = table.getElementsByTagName("tbody")[0];
tbody.onclick = function (e) {
e = e || window.event;
var data = [];
var target = e.srcElement || e.target;
while (target && target.nodeName !== "TR") {
target = target.parentNode;
}
if (target) {
var cells = target.getElementsByTagName("td");
for (var i = 0; i < 2; i++) {
data.push(cells[i].innerHTML);
}
}
alert(data);
};
</script>
</body>
</html>
cat Data_2_54235.txt
Nice Work! Your code is working with first file.
cat Data_2_44235.txt
Nice Work! Your code is working with second file.
how can i implement the above code.
I see you generate a filename based on input values. That means that the ajax call will be made upon that filename, which is odd, becouse you have to create a file with that name.
Anyway, i don't see nowhere in your code that by clicking table rows you make an ajax call, you only save the innerHTML text to a variable data = [] and then alert it. But the problem is not here (if you don't expect to make ajax call when clicking table-rows), but it is inside the ajax call you are making when clicking the button.
first
url:filename
var filename= "Data_"+ID+"_"+Value+".txt";
I strongly suggest you don't do that. It will work if you make an ajax call to a php script which creates that txt file with filename name, and then make another ajax call to that file and fetch it.
second
data: {
ID: $("input#id").val(),
Value: $("input#value").val()
}
look here at data, the doc explains it. the code above means that to filename it will pass parameters (GET parameters, i.e. x?=...), but becouse your file is .txt, this doesn't make sense.
third
$("#tabs").load("demo_test.txt");
This will add the text inside demo_test.txt to $("#tabs") , like innerHTML does or .html() does. Do you have demo_test.txt on your host? i suppose this should work.
just change you ajax call and load call with this. this should work :
$("button").click(function() {
$.ajax({
url : "demo_test.txt",
dataType: "text",
success : function (data) {
$("#tabs").html(data);
}
});
});
For clicking the table-rows, just add an event listener to table-rows, and make an ajax call. read the link i send you, as they are important to understand better what is ajax.
You can see no unnecessary data parameter is thrown to ajax call, and i put there an dataType, meaning that we expect text data to be recieved. If this doesn't work, you have to be sure that you are working on localhost server(for ajax to work...) and you have demo_test.txt , and the url is passed correctly
example using input values to fetch from ajax:
$("button").click(function() {
var id = $("input#id").val();
var value = $("input#value").val();
$.ajax({
url : "Data_" + id + "_" + value + ".txt",
dataType: "text",
success : function (data) {
$("#tabs").html(data);
},
error: function (data) {
#("#tabs").html('No such file found on server');
}
});
});
example of event handler click <tr>
$("table tbody").on("click", "tr", function() {
var id = $(this).find("td")[0].text(); // gets the first td of the clicked tr (this is the ID i suppose)
var value = $(this).find("td")[1].text(); // gets the second td of the clicked tr (this is the VALUE i suppose)
$.ajax({
url : "Data_" + id + "_" + value + ".txt",
dataType: "text",
success : function (data) {
$("#tabs").html(data);
},
error: function (data) {
#("#tabs").html('No such file found on server');
}
});
});

Accessing getElementsByName array after Jquery Ajax IE

I have a table list of companies with a [+] button next to each company name in my table list.
When user clicks [+], a javascript function uses jquery ajax to get and append a new table row below the row clicked, which will then display an indented list of departments.
All works great.. until we get to our beloved IE. I'm using IE 8, not tried this on prev versions.
Table list item HTML before a click:
<tr id="row1">
<td align="center">
<div id="button1" class="on" onclick="javascript:expandDepartments(1)"></div>
</td>
<td>Company 1</td>
</tr>
The onClick function:
<script>
function expandDepartments(s_cid) {
if ($('#button'+s_cid+'').hasClass('on')) {
$('#button'+s_cid+'').removeClass('on').addClass('off');
if ( document.getElementsByName('rowafter'+s_cid+'').length == 0) { //if the department list does not exist for this company (first time getting departments)
$.ajax({
type: 'POST',
url: 'ajax/common.php',
dataType: 'html',
data: 'a=getHomePageDepartments&cid='+s_cid+'',
success: function(txt){
setTimeout(function(){
$('#homeCompaniesList tbody').find('#row'+s_cid+'').after(txt);
},1000);
}
});
}else{ //otherwise, just re-show the row again, no need to request it again
setTimeout(function(){
var x = document.getElementsByName('rowafter'+s_cid+'');
for(var k=0;k<x.length;k++)
x[k].style.display = '';
},1000);
}
} else if ( $('#button'+s_cid+'').hasClass('off') ) { //hide the row when MINUS image clicked
$('#button'+s_cid+'').removeClass('off').addClass('on');
var x = document.getElementsByName('rowafter'+s_cid+'');
alert(x.length);
for(var k=0;k<x.length;k++)
x[k].style.display = 'none';
}
}
</script>
The HTML output for a company containing multiple departments:
<tr style="display:;" name="rowafter1"><*td data not important*..
<tr style="display:;" name="rowafter1">
<tr style="display:;" name="rowafter1">
<tr style="display:;" name="rowafter1">
<tr style="display:;" name="rowafter1">
Now, look at javascript function, line:
alert(x.length);
In Firefox, it alerts 5
In IE it alerts 0
Which tells me, the HTML elements injected into the page using jquery ajax are not accessible in IE and I have no idea why. Do I need to set an ajax parameter for ie?? Not sure.. please assist.
ta
IE has an issue with getElementsByName
Alternatively, why not use jQuery?
var x = $('*[name="rowafter'+s_cid+'"]'); //get all elements with name rowafterN
getElementsByName() does not work in < IE9. If you are using jQuery, use the attribute selector:
var x = $('[name="rowafter' + s_cid + '"]');
alert(x.length);

Categories