Can somebody help me with how can I make my id variable globally? What is wrong here?
var id;
function GenerateTableFromJson(objArray) {
var tableContent =
'<table id="FilesTable" class="table table-striped table-bordered" cellspacing="0" width="100%">' +
'<thead><tr>' + '<th>ID</th>' + '<th>Actions</th>' + '</tr></thead>';
for (var i = 0; i < objArray.length; i++) {
tableContent += '<tr>';
tableContent += '<td>' + objArray[i].Id + '</td>';
tableContent += "<td><a id='" + objArray[i].Id + "' href='#' style='color: orange' class='confirmEditFileLink'>" +
"<i class='glyphicon glyphicon-pencil' title='Edit Item'></i></a>  ";
tableContent += "<a id='" + objArray[i].Id + "' href='#' style='color: red' class='confirmDeleteFileLink'>" +
"<i class='glyphicon glyphicon-remove' title='Delete File'></i></a>  ";
tableContent += "<a id='" + objArray[i].Id + "' href='#' class='confirmListItemDetailsLink'>" +
"<i class='glyphicon glyphicon-cog' title='Link to List Item'></i></a></td>";
tableContent += '</tr>';
var intmaxId = objArray[i].Id;
id = intmaxId;
//windows.id = intmaxId;
return id;
}
return tableContent;
};
console.log(id);
var id;
var idArray=[];
var tableContent;
function GenerateTableFromJson(objArray){
tableContent = '<table id="FilesTable" class="table table-striped table-bordered" cellspacing="0" width="100%">' +
'<thead><tr>' + '<th>ID</th>' + '<th>Actions</th>' + '</tr></thead>';
for (var i = 0; i < objArray.length; i++) {
tableContent += '<tr>';
tableContent += '<td>' + objArray[i].Id + '</td>';
tableContent += "<td><a id='" + objArray[i].Id + "' href='#' style='color: orange' class='confirmEditFileLink'>" +
"<i class='glyphicon glyphicon-pencil' title='Edit Item'></i></a>  ";
tableContent += "<a id='" + objArray[i].Id + "' href='#' style='color: red' class='confirmDeleteFileLink'>" +
"<i class='glyphicon glyphicon-remove' title='Delete File'></i></a>  ";
tableContent += "<a id='" + objArray[i].Id + "' href='#' class='confirmListItemDetailsLink'>" +
"<i class='glyphicon glyphicon-cog' title='Link to List Item'></i></a></td>";
tableContent += '</tr>';
idArray.push(objArray[i].Id);
}
return tableContent;
}
tableContent=GenerateTableFromJson(objArray);
console.log(idArray);
In this sample code id, idArray and tableContent are defined globally. In every iteration your id will be pushed to an array so that you can get entire data after completion of iteration.
if you need find max id then you can use var max = Math.max(...arr);
I also suggest you to use following pattern while creating element rather than appending strings.
var table=$("<table>"); or
var table=document.createElement('table'); which will increase flexibility and readability.
Assuming that code is at the top level of the script, your id variable is global. But it only has its default value (undefined) at the point where you console.log it, because the only code that assigns it a value is in the GenerateTableFromJson function, which nothing in that code calls. Until/unless something calls GenerateTableFromJson, id won't have a value.
There are other issues, such as the fact that your for loop will only ever run once, since you're doing a return from within it, which will exit the function.
Related
I am trying to get my dynamically created HTML table to display text (contained within an array) on hover of a given cell, using the title attribute, but it will not read the contents of the array and instead reads the array name as a string.
Here is the table generating code and have attempted to add titles to cells of 2 columns currently:
var result = "<table id='dataEditTableid' class='stripe' border=1><thead><tr><th><b>Name</b></th><th><b>7.1</b></th><th><b>7.2</b></th><th><b>7.3</b></th><th><b>7.4</b></th><th><b>7.5</b></th><th><b>7.6</b></th><th><b>8.1</b></th><th><b>8.2</b></th><th><b>8.3</b></th><th><b>8.4</b></th><th><b>8.5</b></th><th><b>8.6</b></th><th><b>9.1</b></th><th><b>9.2</b></th><th><b>9.3</b></th><th><b>9.4</b></th><th><b>9.5</b></th><th><b>9.6</b></th></tr></thead>";
result += "<tbody>";
for (var i=0; i < studentsList.length; i++) {
result += "<tr>";
result += "<td>"+studentsList[i][0]+"</td>";
result += "<td title = studentsList[i][3] style='background-color: "+redBlue(studentsList[i][3])+";' id=" + i+3 + "></td>";
result += "<td title = studentsList[i][4] style='background-color: "+redBlue(studentsList[i][4])+";' id=" + i+4 + "></td>";
result += "<td style='background-color: "+redBlue(studentsList[i][5])+";' id=" + i+5 + "></td>";
result += "<td style='background-color: "+redBlue(studentsList[i][6])+";' id=" + i+6 + "></td>";
result += "<td style='background-color: "+redBlue(studentsList[i][7])+";' id=" + i+7 + "></td>";
result += "<td style='background-color: "+redBlue(studentsList[i][8])+";' id=" + i+8 + "></td>";
result += "<td style='background-color: "+redBlue(studentsList[i][9])+";' id=" + i+9 + "></td>";
result += "<td style='background-color: "+redBlue(studentsList[i][10])+";' id=" + i+10 + "></td>";
result += "<td style='background-color: "+redBlue(studentsList[i][11])+";' id=" + i+11 + "></td>";
result += "<td style='background-color: "+redBlue(studentsList[i][12])+";' id=" + i+12 + "></td>";
result += "<td style='background-color: "+redBlue(studentsList[i][13])+";' id=" + i+13 + "></td>";
result += "<td style='background-color: "+redBlue(studentsList[i][14])+";' id=" + i+14 + "></td>";
result += "<td style='background-color: "+redBlue(studentsList[i][15])+";' id=" + i+15 + "></td>";
result += "<td style='background-color: "+redBlue(studentsList[i][16])+";' id=" + i+16 + "></td>";
result += "<td style='background-color: "+redBlue(studentsList[i][17])+";' id=" + i+17 + "></td>";
result += "<td style='background-color: "+redBlue(studentsList[i][18])+";' id=" + i+18 + "></td>";
result += "<td style='background-color: "+redBlue(studentsList[i][19])+";' id=" + i+19 + "></td>";
result += "<td style='background-color: "+redBlue(studentsList[i][20])+";' id=" + i+20 + "></td>";
result += "</tr>";
}
result += "</tbody></table>";
dataTable.innerHTML = result;
What have I done wrong?
result += "<td title='"+ studentsList[i][4] +"' style='background-color: "+redBlue(studentsList[i][4])+";' id=" + i+4 + "></td>";
you've messed quotations, please replace this with the older ones
also, no need to repeat stuff just add another for loop inside the for:
for (var i = 0; i < studentsList.length; i++) {
result += "<tr>";
result += "<td>" + studentsList[i][0] + "</td>";
result += "<td title='"+ studentsList[i][3] +"' style='background-color: "+redBlue(studentsList[i][3])+";' id=" + i+3 + "></td>";
result += "<td title='"+ studentsList[i][4] +"' style='background-color: "+redBlue(studentsList[i][4])+";' id=" + i+4 + "></td>";
for (var j = 4; j = < 20; i++) {
result += "<td style='background-color: " + redBlue(studentsList[i][j]) + ";' id=" + i + j + "></td>";
}
result += "</tr>";
}
I have created one form and form after submitting the value I want to show them in a table. In table I have one section where I want to delete or edit a particular user on a button. But when I am passing the id to that function I am getting error saying that refernece error occurred!
function getEmployeeDetails() {
for (var i = 0; i < userArray.length; i++) {
var tr = "<tr>";
tr +=
"<td class='table-data'/td>" +
userArray[i].id +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].name +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].email +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].gender +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].role +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].english +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].hindi +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].othersLang +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].description +
"</td>" +
"<td class='table-data'/td>" +
"<button onclick='deleteUser( userArray[i].id )'>Delete</button> || <button onclick='editUser( userArray[i].id )'>Edit</button>" +
"</td>" +
"</tr>";
tbody.innerHTML += tr;
}
}
function deleteUser(id) {
console.log("delteuser", typeof id, id);
}
function editUser(id) {
console.log("edit", id);
}
Where I have made the mistakes?
The problem is in the string concatenation you are using in the onClick event.
You can use a backtick character instead.
Copy-paste and check the below code.
<html>
<body>
<table id="table"></table>
<script>
getEmployeeDetails();
function getEmployeeDetails() {
let userArray = [{ id: 1 }, { id: 2 }];
var tr = "";
for (var i = 0; i < userArray.length; i++) {
tr +=
`<td class="table-data">
<button onclick="deleteUser(` +
userArray[i].id +
`)">Delete</button> || <button onclick="editUser( ` +
userArray[i].id +
`)">Edit</button>
</td>`;
}
document.getElementById("table").innerHTML = tr;
}
function deleteUser(id) {
console.log("delteuser", typeof id, id);
}
function editUser(id) {
console.log("edit", id);
}
</script>
</body>
</html>
Change
<button onclick='deleteUser( userArray[i].id )'>
To something like
<button onclick='deleteUser('+userArray[i].id+')'>
In your current attempt you are not inserting the value of userArray[i].id but the variable userArray[i].id which is kind of nonsense.
Same story with the editUser function
I fixed the problem by calling a function, that graps the id of the table row it is placed in :)
I have this piece of code sorting some different stuff into a table, that works fine. The problem is to pass data into a function called inside HTML tags, like so:
See reference here
$.when(document, getTournamentsData()).done(function(){
var output = "";
$.each(tournamentsData, function(key, data){
output += "<tr class='data_row "+data.isOpen+"' id='"+data._id+"'>";
output += "<td>" + (key+1) + "</td>";
output += "<td><b>" + data.name + "</b></td>";
output += "<td>Start: " + data.begintime + "<br>Slut: " + data.endtime + "</td>";
output += "<td><input class='btn btn-primary' type='button' value='Se beskrivelse' onclick='showTourDescription(data.description)'/></td>";
output += "<td><input class='btn btn-primary' type='button' value='Se billede' onclick='showPic(data.image)'/></td>";
output += "<td>Max antal: "+ data.max_teams +"<br>Tilmeldte: "+ data.teams.length +"</td><br>";
output += "<td><input class='btn btn-primary' type='button' value='Se deltagere' onclick='showMembers(data.teams)'/></td>";
output += "<td>" + prizes(data.prices) + "</td>";
output += "</tr>";
});
output += "";
$('#data_insert').append(output);
});
All I do in the function is to console the data, and I get error "data is not defined"
This is the full script https://github.com/Jakobtottrup/OptekSemester2/blob/master/Web/public/js/tournaments_admin.js
// list tournaments
$.when(document, getTournamentsData()).done(function(){
var output = "";
$.each(tournamentsData, function(key, data){
output += "<tr class='data_row "+convertBoolean(data.isOpen)+"' id='"+data._id+"'>";
output += "<td>" + (key+1) + "</td>"; // index
output += "<td><b>" + data.name + "</b></td>"; // navn
output += "<td>Start: " + data.begintime + "<br>Slut: " + data.endtime + "</td>"; // start/slut
output += "<td><input class='btn btn-primary' type='button' value='Se beskrivelse' onclick='showTourDescription("+data.description+")'/></td>"; // beskrivelse TODO
output += "<td><input class='btn btn-primary' type='button' value='Se billede' onclick='showPic("+data.description+")'/></td>"; // billede
output += "<td>Max antal: "+ data.max_teams +"<br>Tilmeldte: "+ data.teams.length +"</td><br>"; // hold
output += "<td><input class='btn btn-primary' type='button' value='Se deltagere' onclick='showMembers("+data.teams"+)'/></td>"; // medlemmer
output += "<td>" + prizes(data.prices) + "</td>"; // præmier
output += "</tr>";
});
I've taken your code, and as you've done in the HTML strings themselves, concatenated in the event handlers too. Should be all you need to do.
UPDATE: Looks like you are passing data as string. See if that works
$.each(tournamentsData, function(data) {
onclick='showTourDescription(" + data.description + ")
I have a php scripts which shows data from worldoftanks api server. I show this data in table so I would like to add image near every user whos rank is "Recruit".
This is my javascript for table:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "POST",
url: "clan_info.php",
success: function(data){
var htmlString = '<table cellpadding="0px" class="menu1"><tr><th>Username</th><th>Rank</th><th>PR</th><th>BTL</th><th>W/B</th><th>E/B</th><th>Days</th></tr>';
var clanData = JSON.parse(data);
i = 0;
for(userID in clanData){
userData = clanData[userID];
var extraClass = '';
if(i < 3) {
extraClass = 'class="rank' + (i+1) + '"';
}
htmlString += '<tr>';
htmlString += '<td '+extraClass+'>' + userData['name'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['role'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['rating'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['battles'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['w_p_b'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['xp_p_b'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['days'] + '</td>';
htmlString += '</tr>';
i++;
}
htmlString += '</table>';
console.log(htmlString);
$("#wot").html(htmlString);
}
});
});
</script>
AND MY PHP SCRIPT:
<?php
$clanID = "500006494";
$clanApiPage = "https://api.worldoftanks.eu/wgn/clans/info/?application_id=demo&clan_id=$clanID";
$userApiPage = "https://api.worldoftanks.eu/wot/account/info/?application_id=demo&account_id=";
$clanStrongHoldPage = "https://developers.wargaming.net/reference/all/wot/stronghold/info?application_id=demo&clan_id=$clanID";
$getAndDecode = function($url) {
$jsonData = file_get_contents($url);
$dataArray = json_decode($jsonData, true);
return $dataArray;
};
$determineDays = function($date) {
$datediff = time() - $date;
return floor($datediff/(60*60*24));
};
$jsonData = $getAndDecode($clanApiPage) , ($clanStrongHoldPage);
$clanAccounts = array();
foreach($jsonData["data"][$clanID]["members"] as $memberArray) {
$accountID = $memberArray["account_id"];
$clanAccounts[$accountID]['id'] = $memberArray["account_id"];
$clanAccounts[$accountID]['role'] = $memberArray["role_i18n"];
$clanAccounts[$accountID]['name'] = $memberArray["account_name"];
$clanAccounts[$accountID]['days'] = $determineDays($memberArray["joined_at"]);
}
$accountIDs = implode(",", array_keys($clanAccounts));
$apiPage = $userApiPage . $accountIDs;
$userJsonData = $getAndDecode($apiPage);
foreach($userJsonData["data"] as $userID => $dataArray) {
$playerStatistic = $dataArray["statistics"]["all"];
$clanAccounts[$userID]['rating'] = $dataArray["global_rating"];
$clanAccounts[$userID]['battles'] = $playerStatistic["battles"];
$clanAccounts[$userID]['w_p_b'] = $playerStatistic["wins"]/$playerStatistic["battles"] * 100;//wins per battle
$clanAccounts[$userID]['xp_p_b'] = $playerStatistic["battle_avg_xp"]; //experience per battle
}
$w_p_b = array();
foreach ($clanAccounts as $userID => $row) {
$w_p_b[$userID] = $row['w_p_b'];
}
array_multisort($w_p_b, SORT_DESC, $clanAccounts);
die(json_encode($clanAccounts));
?>
my table sample here: http://www.slovenian-army.tk/members.html
I would like to put image near every user like this:
sloa_clan
Depends on what rank is user. If user is Comander he gets comanders icon
If user is Recruit he gets Recruit icon.
Thank you!
I find out how to do this.
by adding this var:
var username = '<img src="images/' + userData['role'] + '.png" height="25" width="25" />' + userData['name'];
and code now looks like:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "POST",
url: "clan_info.php",
success: function(data){
var htmlString = '<table cellpadding="0px" class="menu1"><tr><th>Username</th><th>Rank</th><th>PR</th><th>BTL</th><th>W/B</th><th>E/B</th><th>Days</th></tr>';
var clanData = JSON.parse(data);
i = 0;
for(userID in clanData){
userData = clanData[userID];
var extraClass = '';
if(i < 3) {
extraClass = 'class="rank' + (i+1) + '"';
}
var username = '<img src="images/' + userData['role'] + '.png" height="25" width="25" />' + userData['name'];
htmlString += '<tr>';
htmlString += '<td '+extraClass+'>' + username + '</td>';
htmlString += '<td '+extraClass+'>' + userData['role'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['rating'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['battles'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['w_p_b'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['xp_p_b'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['days'] + '</td>';
htmlString += '</tr>';
i++;
}
htmlString += '</table>';
console.log(htmlString);
$("#wot").html(htmlString);
}
});
});
</script>
I have dynamically generated table using jquery. I want a cell of the table be converted to a textbox when clicked.
$.each(proc_msg, function (i, item) {
trHTML += "<tr><td>" + item.hq_code + "</td><td id='hq_" + item.hq_name + "'>" + item.hq_name + "</td>";
trHTML += "<td><a href='#' id='hq_ed_" + item.hq_name+_"' onClick='dataAction(this.id);'>Edit</span></a></td>";
});
$('#tbl_hqlist').append(trHTML);
function dataAction(dataValue){
var sectionName=dataValue.substr(0,2);
var hq_zone=dataValue.substr(5);
var zone_id ="";
zone_id= zone_id.concat("'#",sectionName, hq_zone,"'");
var tempHTML ="<input type='text' id='" + zone_id + "' value='" + hq_zone + "' />";
$(zone_id).html(tempHTML);
}
This code is throwing up error where "zone_id" is not defined.