jquery how to add image in table TD near specified text - javascript

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>

Related

Call a function passing a file name from dynamically created table

I am trying to pass a file name from dynamically created table and getting some Uncaught ReferenceError: Q1_58_English_Resume is not defined
at HTMLAnchorElement.onclick (AddRequirement:1)
Here the file name is "Q1_58_English_Resume"
The script for dynamic table is below
if (filesData.length > 0) {
var table = '';
table += '<table class="radar-grid-table" id="TableAttach">';
table += '<thead>';
table += '<tr>';
table += '<th>Files</th>'
//table += '<th>Select</th>';
table += '<th>Actions</th>';
table += '</tr>';
table += '</thead>';
table += '<tbody>';
$.each(filesData, function (i, item) {
table += '<tr>';
table += '<td>' + item + '</td>';
//table += '<td title="' + item.AttachmentId + '">' + item.AttachmentId + '</td>';
//<input value="' + full.QuestionId + '
table += '<td> Download </td>';
table += '</tr>';
});
table += '</tbody>';
table += '</table>';
return table;
}
And the Function is below:
function DownloadAttachment(fileName) {
debugger;
var url = "/RequirementManagement/OpenFile?ids=" + fileName;
window.location.href = url;
}
Try this , should work
var table = '';
table += '<table class="radar-grid-table" id="TableAttach">';
table += '<thead>';
table += '<tr>';
table += '<th>Files</th>'
//table += '<th>Select</th>';
table += '<th>Actions</th>';
table += '</tr>';
table += '</thead>';
table += '<tbody>';
$.each(filesData, function (i, item) {
table += '<tr>';
table += '<td>' + item + '</td>';
//table += '<td title="' + item.AttachmentId + '">' + item.AttachmentId + '</td>';
//<input value="' + full.QuestionId + '
table += '<td> Download </td>';
table += '</tr>';
});
table += '</tbody>';
table += '</table>';
return table;
}

JS variable not working in AJAX success

Fetched data from database with php and ajax, Everything is ok except note variable is empty.Can somebody find out the issue why note value is not going to display. How can i fix it.
success: function(response) {
var cats = {};
response.results.forEach(function(element) {
cats[element.team] = cats[element.team] || [];
cats[element.team].push(element);
});
var i = 0;
Object.keys(cats).forEach(function(team) {
let html = '';
// Append the category header
html = '<tr>';
html += '<td>' + team + '</td>';
html += '</tr>';
$('table').append(html);
// Loop through the results for this category
cats[team].forEach(function(element) {
var id = element.id;
var teamId = element.team_id;
var names = element.player;
var result = element.result;
var note = element.note;
html = '<tr>';
html += '<input type="hidden" name="Id[]" value="' + id + '"/>';
html += '<input type="hidden" name="data[' + i + '][team_id]" value="' + teamId + '"/>';
html += '<td>' + names + '</td>';
html += '<td><input type="text" name="result[]" value="' + result + '"></td>';
html += '</tr>';
$('table').append(html);
});
// Append the textarea at the end of the results
html = '<tr>';
html += '<td><textarea placeholder="note..." name="data[' + i + '][Note]">' + note + '</textarea></td>';
html += '</tr>';
$('table').append(html);
i++;
});
}
This is the output
database table
JSON output
{"groupData":{"id":"23","group_name":"Group B"},"results":
[{"id":"2","team_id":"4","team":"Team
B","player":"Deno","result":"14","note":"Lost"},
{"id":"3","team_id":"4","team":"Team
B","player":"Niob","result":"26","note":"Lost"},
{"id":"4","team_id":"4","team":"Team
B","player":"Skion","result":"76","note":"lost"},
{"id":"5","team_id":"5","team":"Team
C","player":"Bela","result":"47","note":"won"},
{"id":"6","team_id":"5","team":"Team
C","player":"yomi","result":"57","note":"won"}]}
You should set note value infront of cats[team].forEach(function(element) {}). Hope to help, my friend :))
success: function(response) {
var cats = {};
response.results.forEach(function(element) {
cats[element.team] = cats[element.team] || [];
cats[element.team].push(element);
});
var i = 0;
Object.keys(cats).forEach(function(team) {
let html = '';
// Append the category header
html = '<tr>';
html += '<td>' + team + '</td>';
html += '</tr>';
$('table').append(html);
var note;
// Loop through the results for this category
cats[team].forEach(function(element) {
var id = element.id;
var teamId = element.team_id;
var names = element.player;
var result = element.result;
note = element.note;
html = '<tr>';
html += '<input type="hidden" name="Id[]" value="' + id + '"/>';
html += '<input type="hidden" name="data[' + i + '][team_id]" value="' + teamId + '"/>';
html += '<td>' + names + '</td>';
html += '<td><input type="text" name="result[]" value="' + result + '"></td>';
html += '</tr>';
$('table').append(html);
});
// Append the textarea at the end of the results
html = '<tr>';
html += '<td><textarea placeholder="note..." name="data[' + i + '][Note]">' + note + '</textarea></td>';
html += '</tr>';
$('table').append(html);
i++;
});
}

Seeking help on syntax error with js string concatenation

I'm trying to toggle between the innerHTML of a table data cell from an AJAX output from onclick row event:
JS:
...
var thisrownumber = 0;
var detailednote = '';
var simplifiednote = '';
htmlStr += '<table>';
$.each(data, function(k, v){
thisrownumber ++;
detailednote = v.note_ids;
simplifiednote = '<img class="See" src="~.png" alt="See" style="width:20px; height:20px;"> See';
htmlStr += '<tr onclick="shrow(' + thisrownumber + ',' + detailednote + ',' + simplifiednote + ')">'
+ '<td>' + v.date + '</td>'
+ '<td>' + v.r + '</td>'
+ '<td>' + v.f + ': ' + v.s + '</td>'
+ '<td>' + '<span id="span_note' + thisrownumber + '">' + simplifiednote + '</span>'
+ '</td>'
+ '</tr>';
});
htmlStr += '</table>';
$("#content").html(htmlStr);
} // function close
function shrow(x,y,z){
var lang3 = "span_note";
var shrow = x;
var span_note = lang3.concat(x);
if(document.getElementById(span_note).innerHTML == y){
document.getElementById(span_note).innerHTML = z;
}
if(document.getElementById(span_note).innerHTML == z){
document.getElementById(span_note).innerHTML = y;
}
}
HTML:
<div id="content"></div>
Getting error:
Uncaught SyntaxError: missing ) after argument list

Javascript - return dynamic row data with checkbox input

I seem to only be able to find the answer to this problem in JQuery and I would really like a pure JS solution.
I have a dynamically generated table that I build from a parsed JSON file. I added a checkbox for each row. My question is, do I also have to generate a unique ID or Class for each cell? How can I return a variable containing the data from just the row selected?
var watchLog = new XMLHttpRequest();
var rowChecked;
watchLog.onreadystatechange = function () {
if(watchLog.readyState === 4) {
var status = JSON.parse(watchLog.responseText);
var watchLogCell = '';
for (var i = 0; i < status.length; i += 1) {
watchLogCell += '<tr>';
watchLogCell += '<th scope="row" class="rowHeader"><input type="checkbox" name="selectRow' + i + '"
onclick="function rowData(){if(this.checked){rowChecked = ' + status[i]["Load ID"] + '; return console.log(rowChecked);};">';
watchLogCell += '<td>' + status[i]["Load ID"] + '</td>';
watchLogCell += '<td>' + status[i]["Carrier Name"] + '</td>';
watchLogCell += '<td>' + status[i]["Original PU Date"] + '</td>';
watchLogCell += '<td>' + status[i]["Current PU Date"] + '</td>';
watchLogCell += '<td>' + status[i]["Vendor Name"] + '</td>';
watchLogCell += '<td>' + status[i]["Original DO Date"] + '</td>';
watchLogCell += '<td>' + status[i]["Current DO Date"] + '</td>';
watchLogCell += '<td>' + status[i]["Load Status"] + '</td>';
watchLogCell += '<td>' + status[i]["Truck Status"] + '</td>';
watchLogCell += '<td>' + status[i]["DA First"] + '</td>';
watchLogCell += '<td>' + status[i]["PO Number"] + '</td>';
watchLogCell += '<td>' + status[i]["Buyer No"] + '</td>';
watchLogCell += '<td>' + status[i]["Comments"] + '</td>'
watchLogCell += '</tr>';
}
document.getElementById('tableBody').innerHTML = watchLogCell;
}
};
watchLog.open('GET', 'watchlogic.json');
watchLog.send();
You can try something like
//use this to store the mapping of values, assuming loadid is unique for each record else a unique property of the record has to be used
var watchlogic = {};
var watchLog = new XMLHttpRequest();
watchLog.onreadystatechange = function () {
if (watchLog.readyState === 4) {
var status = JSON.parse(watchLog.responseText);
var watchLogCell = '';
for (var i = 0; i < status.length; i += 1) {
//store the record in watchlogic with key as the unique value
watchlogic[status[i]["Load ID"]] = status[i];
watchLogCell += '<tr>';
watchLogCell += '<th scope="row" class="rowHeader"><input type="checkbox" name="selectRow' + i + '" onclick="onSelect(this)" data-loadid="' + status[i]["Load ID"] + '">'; //store the current record's unique value in an attribute
watchLogCell += '<td>' + status[i]["Load ID"] + '</td>';
watchLogCell += '<td>' + status[i]["Carrier Name"] + '</td>';
watchLogCell += '<td>' + status[i]["Original PU Date"] + '</td>';
watchLogCell += '<td>' + status[i]["Current PU Date"] + '</td>';
watchLogCell += '<td>' + status[i]["Vendor Name"] + '</td>';
watchLogCell += '<td>' + status[i]["Original DO Date"] + '</td>';
watchLogCell += '<td>' + status[i]["Current DO Date"] + '</td>';
watchLogCell += '<td>' + status[i]["Load Status"] + '</td>';
watchLogCell += '<td>' + status[i]["Truck Status"] + '</td>';
watchLogCell += '<td>' + status[i]["DA First"] + '</td>';
watchLogCell += '<td>' + status[i]["PO Number"] + '</td>';
watchLogCell += '<td>' + status[i]["Buyer No"] + '</td>';
watchLogCell += '<td>' + status[i]["Comments"] + '</td>'
watchLogCell += '</tr>';
}
document.getElementById('tableBody').innerHTML = watchLogCell;
}
};
watchLog.open('GET', 'watchlogic.json');
watchLog.send();
function onSelect(el) {
//here el is the clicked element then use the data attribute value to get the unique valeu of the record and use that to get the record form the watchlogic object
var status = watchlogic[el.dataset.loadid]; //or this.getAttribute('data-loadid') for <= IE10
console.log(status)
}

get drop down box attributes

In the below i have a a div with employee names and ahave to assign a grade for them,my question is that i have get the empid for all the selected values in getgrade_values function.Using jquery how to get the ids of the drop down box with its value where the values are selected when on click of evaluate function
function getgrade_values(empid)
{
var ele='<select id="'+ empid +'" name="emp" style="width:40px;margin:0px 0pt;" >';
ele += '<option value=""></option>';
ele += '<option value="A">A</option>';
ele += '<option value="B">B</option>';
ele += '<option value="C">C</option>';
ele += '<option value="D">D</option>';
ele += '<option value="E">E</option>';
ele += '<option value="F">F</option>';
ele += '</select>';
return ele;
}
function sendparams(data)
{
if(data.status == 1)
{
var ele='<tr id="std"><td><b>Evaluate:</b></label> </td></tr>';
for(var l=0;l<data.emparr.length;l++)
{
ele += '<tr><td><div id="'+ data.emparr[l].id +'">' + data.emparr[l].name + "</td><td>" + getgrade_values(data.emparr[l].id) + '</div></td></tr>';
ele+= '<input type="button" value="Evaluate" onclick="evaluate();"';
}
}
var select = $('select[name="emp"]')
var empId = select.attr('id')
alert('empId = '+empId)
select.children('option:selected').each(function() {
alert('grade selected = ' + $(this).val())
})
DEMO : http://jsfiddle.net/hdTEP/
Currently, you will have 2 elements with id="<employeeId>". As ids should be unique across an entire page, you should consider appending the type of element you are representing, for example id="<employeeId>_gradeInput" for your grade dropdown. Next, for each user it seems like you have a button to submit a grade. I would call evaluate with the employee id associated with that button.
function getgrade_values(empid){
var ele='<select id="'+ empid +'_gradeInput" name="emp" style="width:40px;margin:0px 0pt;" >';
..//Remaining code
}
function sendparams(data) {
if (data.status == 1) {
var ele =
'<tr id="std">' +
'<td>' +
'<b>Evaluate:</b>' +
'</td>' +
'</tr>';
for (var l = 0; l < data.emparr.length; l++) {
var employeeId = data.emparr[l].id;
ele +=
'<tr>' +
'<td>' +
'<div id="' + employeeId + '_divContainer">' +
data.emparr[l].name +
'</div>'
'</td>' +
'<td>' +
getgrade_values(employeeId)
'</td>' +
'</tr>';
ele += '<input type="button" value="Evaluate"
onclick="evaluate(' + employeeId + ');"';
}
}
function evaluate(employeeId){
var gradeValue = $('#' + employeeId + '_gradeInput').val();
..//Your other evaluate code here
}

Categories