Replace table instead of append jquery - javascript

I have the following code segment that grabs user input from an HTML form, and then reads a CSV file, and grabs corresponding data to display to my website. If I submit another 'searchTerm' after the initial one in my form, it appends the new row of data from the csv file to the page, and I want it to replace instead. When I try to replace the row however, all my data vanishes.
function submitForm(){
nameValue = document.getElementById("searchTerm").value;
//document.getElementById("display-results").innerHTML = nameValue;
location.href = "#page-3";
function arrayToTable(tableData) {
var table = $('<table></table>');
$(tableData).each(function (i, rowData) {
var row = $('<tr></tr>');
$(rowData).each(function (j, cellData) {
if (cellData == nameValue) {
row.append($('<td>'+rowData[1]+'</td>'));
}
});
table.append(row);
});
return table;
}
$.ajax({
type: "GET",
url: "mainFile.csv",
success: function (data) {
parsed = Papa.parse(data).data;
$('#display-results').append(arrayToTable(Papa.parse(data).data));
}
});
}
As you can see in the image, it appends the content rather than replacing the first array.

Remember to just replace the table, not the entire display-results element (except the first time you build the table).
if($('#display-results table').length === 0) // append if you haven't built the table yet
$('#display-results').append(arrayToTable(Papa.parse(data).data));
else
$('#display-results table').replaceWith(arrayToTable(Papa.parse(data).data));

Related

Why Dropdown list data is refilling with same values, initially I'm loading the data using page_load and next calling ajax method in asp.net c#

Initially I'm loading the ddl data using page_load and next I'm using the AJAX method and fetching the dependency data using Web Method so when I'm selecting the dependency data using `AJAX' the data is coming but the ddl is filling with previous loaded dll data I'm not sure what is the issue.
Here is my code and examples :-
Initially I'm loading the ddl data using page_load event
if (!IsPostBack)
{
firstexpdate = GetExpDates("nifty", "ce");
firststrikeprice = GetStrikePrice("nifty", firstexpdate);
lotsize = GetLotSizeVal("nifty", firstexpdate);
ltpprice = GetGreeksPrice("nifty", firstexpdate, "ce");
}
Like below I'm getting the ddl data.
And here "NIFTY" textbox is autocomplete textbox if I enter minLength: 3 this logic will execute and once enter the acc the autocomplete logic will fire and able to fetching the data from WebMethod and next I'm calling the AJAX method(because once we select the autocomplete textbox data the next ce,date,13500 ... controls data should fill autometically) for auto filling the data.
Here is how I calling the AJAX method logic
$(document).ready(function () {
//Initially I'm calling this function
autocomplete();
//Page load even I written because I used all control under the `updatepanel`
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
autocomplete();
}
});
function autocomplete() {
$("#search").autocomplete({
source: function (request, response) {
// my source logic is here and able to fetching the data successfully
//once I fetch all the symbols and next I'm calling this method
doSearch(suburbs); //Calling the Symbol Display Method{in this suburbs I'm filling the response data}
},
minLength: 3 //This is the Char length of inputTextBox
});
}
function doSearch(suburbs) {
//And here I written all my required logic and next I'm calling this method for auto fill data
//Like how I explained above query
var smbltext = $(this).text(); //Here will come `ACC` Symbol in autocomplete textbox
AutoFillUsingSymbol(smbltext); // Filling the dependency fields data
}
//This is the full logic of auto filling the controls once we select the`autocomplete`textbox data
function AutoFillUsingSymbol(symbol) {
if (symbol != '') {
var paramsmbl = { entredsmbl: symbol, selectedinstrument: $('#AutoTradeTop_Instrument option:selected').text()};
//alert(paramsmbl.entredsmbl);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "AutoTrade.aspx/AutoFillData",
data: JSON.stringify(paramsmbl),
dataType: "json",
dataFilter: function (data) {
return data;
},
success: function (data) {
//Clearing before filling the data into ddl
$('#AutoTradeTop_expdate').empty();
$('#AutoTradeTop_strikeprice').empty();
$('#autotrade_lotsizeid').html('');
$('#LTPliveAmount').html('');
var length = data.d.length;
//data.d.each(function (index, element) {
//}
$.each(data.d, function (key, value) {
//alert(value);
if (value.indexOf("-") != -1) {
//alert(value + "date found");
$("#AutoTradeTop_expdate").append($("<option></option>").val(key).html(value));
}
else {
if (!(key == length - 2 || key == length - 1)) {
//alert(value + " value found ");
$("#AutoTradeTop_strikeprice").append($("<option></option>").val(key).html(value));
}
else {
if (key == length - 2) {
//alert(value + "LotSizeVal found");
$('#autotrade_lotsizeid').html(value);
}
else if (key == length - 1) {
//alert(value + "LTP Price found");
$('#LTPliveAmount').html(value);
}
}
}
});
},
error: function ajaxError(data) {
alert(data.status + ' : ' + data.statusText);
}
});
}
}
Once this AJAX logic hit AutoFillUsingSymbol(symbol) It will go to WebMehod logic and able to fetching the required data and filling into ddl list.
before filling into ddl data I'm clearing(emptying the dropdown list data) the ddl data and refilling
$('#AutoTradeTop_expdate').empty();
$('#AutoTradeTop_strikeprice').empty();
$('#autotrade_lotsizeid').html('');
$('#LTPliveAmount').html('');
Here is the example image of auto filling data once we select acc symbol and date is loading what I selected symbol acc
But if I select any one date the dropdown list data is clearing and filling the previous symbol data `nifty' see the above first image for reference.
example image
Note :- I know if we fill or change the dropdownlist client side code, then the list of values does not persist but initially I filled the ddl data in the page_load event and next I wrote the AJAX method but why the values are not loading properly.
Suggest me what is the issue and where I did the mistake
I'm beginner in the client side code development .

How to set download url in a table row

I've this javascript function that takes the ajax call's result and build a html table with it. This table rapresents list of reports.
Each row of a table is composed by report's filename and date of creation, and when I click over it a new browser page is opened showing me the document. But I want to download it. How can I get it?
Code:
function report_call(){
$.ajax({
type: 'GET',
url: "/rest/v2/reports/",
dataType: 'json',
success: function (data) {
$("#modal-body").html('')
const YOURREPORTS_ROW = "yourReportRow";
const YOURREPORTS_TABLE = "yourReports-table-content";
let table = $(`#${YOURREPORTS_TABLE}`);
table.html('')
for(const key in data) {
if(data[key].length == 0){
continue
}
data[key].forEach(report_type => {
let url = report_type[2] // take file url
let fname = report_type[0];
let fname_td = $(`<td>${fname}</td>`);
let date = report_type[1];
let date_td = $(`<td>${date}</td>`);
let onclick = "";
if(url !== ""){
onclick = `onclick="window.open('${url}', '_blank');"`;
}
let row = $(`<tr class="${YOURREPORTS_ROW}" [data-file="${fname}"] data-date="${date}" ${onclick}>`);
row.append(fname_td);
row.append(date_td);
table.append(row);
})
}
}
})
}
On the web I read that I can use "download" keyword in tag , but here the situation is different. I try in this way, it does not work.
Sorry for the ignorance.
Use an anchor tag with download attribute like below. You can also add another td for the download link. Remove the onClick event in row.
let date_td = $(`<td>${date} <a href=${url} download>Download</a></td>`);

Select Row from table with JSON values using JQuery

I have JSON data from an MVC controller with the values
[{"OperationName":"All","PrivilegeName":"Roles Crud"},{"OperationName":"Read","PrivilegeName":"Roles Read Delete"},{"OperationName":"Delete","PrivilegeName":"Roles Read Delete"},{"OperationName":"Read","PrivilegeName":"Roles Update"},{"OperationName":"Update","PrivilegeName":"Roles Update"}]
I have Displayed this JSON data into an HTML table using AJAX.
$(document).ready(function () {
//debugger;
$.ajax({
url: "/Home/GetOpPriv",
type: "GET",
contentType: "application/json; charset=utf-8",
data: "source={}",
dataType: "json",
success: function (data) {
var row = "";
$.each(data, function (index, item) {
row += "<tr id='trName_" + index + "'>";
row += "<td id='td_OpName" + index + "'>" + item.OperationName + "</td>";
row += "<td id='td_PrivName" + index + "'>" + item.PrivilegeName + "</td>";
row += "<tr>";
});
$("#table1").html(row);
console.log(data);
var source = [];
source.push(data);
console.log(source);
},
error: function (result) {
alert("Error");
}
})
});
I'm Trying to select individual rows from the table when I click the particular row, it should display its value in the alert box
But instead, it's displaying the entire table JSON data onClick.
What correction should I make to this JQuery Function?
$(document).ready(function () {
$("#table1 tr").click(function () {
debugger;
$('.selected').removeClass('selected');
$(this).parents('tr').addClass('selected');
})
});
As I understand your question, you want to display the selected row data, for this scenario, you can try like this
$("#table1 tr").click(function () {
$('.selected').removeClass('selected');
$(this).addClass('selected');
var _index = $(this).attr("id").replace("trName_", "");
var _currentSelectedRow = source[_index];
console.log(_currentSelectedRow);
});
And in ajax success block you are declaring the variable as
var source = [];
source.push(data);
Instead of this declare the 'source' variable as global variable and assign the json data to 'source' in ajax success block.
source = data;
If I understand your question correctly, then the solution is this:
$(document).ready(function () {
$("#table1 tr").click(function () {
$('.selected').removeClass('selected');
$(this).addClass('selected'); // remove .parents('tr')
})
});
By making the change above, this will cause only the row that the user clicks in #table1 (i.e. the row element corresponding to $(this) ) to have the selected class applied.
You are guaranteed to have $(this) inside of your click handler correspond to a table row element, seeing that the click handler is bound to tr elements via the #table tr selector. Hope this helps!

Reading in a specific csv file into html

I'm currently trying to select a specific csv file based on user selection and then display this as a html table in the web page on the click of a button.
The steps that this will need to have are:
to select the options from a drop down which will be used to identify the csv file name
pass the csv file name to a function which displays this as a html table
perform this on the click of a button rather than when the web page loads
Below is the code I have so far, the first part of the code identifies the csv file name.
The second part reads in a hard coded csv file and parses it as a html table which is displayed when the web page opens.
<script>
function button_clicked(){
var obj_opt = document.getElementById("opt");
var opt = obj_opt.value;
if (opt==""){
alert("Please select Option1");
return;
}
var obj_opt_two = document.getElementById("opt_two");
var opt_two = obj_opt_two.value;
if (opt_two==""){
alert("Please select Option2");
return;
}
var urls= "http://mysite/" + opt + "_" + opt_two + ".csv";
alert("The link is: " + urls);
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.2/papaparse.js"></script>
<script>
function arrayToTable(tableData) {
var table = $('<table></table>');
$(tableData).each(function (i, rowData) {
var row = $('<tr></tr>');
$(rowData).each(function (j, cellData) {
row.append($('<td>'+cellData+'</td>'));
});
table.append(row);
});
return table;
}
$.ajax({
type: "GET",
url: "http://mysite/Option1_Option2.csv",
success: function (data) {
$('body').append(arrayToTable(Papa.parse(data).data));
}
});
</script>
<button type="button" onClick="button_clicked()">Load New File</button>
I am unsure how to combine the two javascripts to load the user selected csv as a table via a button, any help on how to do this would be greatly appreciated!
To make this work you need to move the $.ajax logic in to the button click handler, and apply the url value to it.
Also note that using on* event attributes in HTML is very outdated and should be avoided where possible. You should use unobtrusive event handlers instead. As you've already included jQuery in the page, you can use that:
$(function() {
$('#load').click(function() {
var opt = $("#opt").val();
if (!opt) {
alert("Please select Option1");
return;
}
var opt_two = $("#opt_two").val();
if (!opt_two) {
alert("Please select Option2");
return;
}
$.ajax({
type: "GET",
url: `http://mysite/${opt}_${opt_two}.csv`,
success: function(data) {
$('body').append(arrayToTable(Papa.parse(data).data));
}
});
});
function arrayToTable(tableData) {
var html = tableData.map(function(row) {
var rowHtml = '<tr>';
row.forEach(function(cell) {
rowHtml += `<td>${cell}</td>`;
});
return rowHtml + '</tr>';
});
return `<table>${html.join('')}</table>`;
}
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.2/papaparse.js"></script>
<button type="button" id="load">Load New File</button>
Finally, note that jQuery 1.7 is rather old now. I'd suggest upgrading to 1.12 if you still need to support older IE browsers, or 3.2.1 if not.
Move the
$.ajax({
type: "GET",
url: "http://mysite/Option1_Option2.csv",
success: function (data) {
$('body').append(arrayToTable(Papa.parse(data).data));
}
});
in the place of
alert("The link is: " + urls);

Generate HTML code from data stored in csv, xml or json

What I have: a csv (can be converted to xml or maybe to json) file that has many rows, each row contains several columns that store data about some profile.
What I need to do: to generate an html page that corresponds to each row automatically given the html elements' layout. Since I may have hundreds of rows and all pages got identical html elements (I mean, like an imdb or facebook profile) except the unique profile data shown to users, a small change to the layout of a page later would require days of stupid manual work.
Is there some kind of framework that can do what I seek to do? Thank you!
The process
You need three steps :
1) Use Ajax to fetch data from your server and turn it into an array. You could do this eg. with the following jQuery :
$.ajax({
type: "GET",
url: "data.csv",
success: CSVToHTMLTable
});
2) Once you have get your file, you need to parse it. Json and XML support are native in JavaScript. An easy & reliable way to do it for a CSV file, would be to use a library like Papa Parse :
var data = Papa.parse(data).data;
3) You need to define a function to transform your array into an HTML table. Here's how you could do this with jQuery :
function arrayToTable(tableData) {
var table = $('<table></table>');
$(tableData).each(function (i, rowData) {
var row = $('<tr></tr>');
$(rowData).each(function (j, cellData) {
row.append($('<td>'+cellData+'</td>'));
});
table.append(row);
});
return table;
}
Putting everything together
Here's how you can put everything together :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.2/papaparse.js"></script>
<script>
function arrayToTable(tableData) {
var table = $('<table></table>');
$(tableData).each(function (i, rowData) {
var row = $('<tr></tr>');
$(rowData).each(function (j, cellData) {
row.append($('<td>'+cellData+'</td>'));
});
table.append(row);
});
return table;
}
$.ajax({
type: "GET",
url: "http://localhost/test/data.csv",
success: function (data) {
$('body').append(arrayToTable(Papa.parse(data).data));
}
});
</script>
I'd suggest json2html if you can convert your csv to json.

Categories