How do I copy text to the clipboard in JS? - javascript

I would like to put a copy paste on the email, when clicking on the email, the email is copied automatically. I've tried several techniques but I can't.
Here is my code:
content += '<table class="table"><thead><tr><th>Nom</th><th>Prénom</th><th>Companie</th><th>Tags</th><th class="copy">Email</th></tr></thead><tbody>';
JSON.parse(data).forEach(id => {
content += '<tr>';
content += '<td>' + id.lastname + '</td>';
content += '<td>' + id.firstname + '</td>';
content += '<td>' + id.company + '</td>';
content += '<td>' + id.tags + '</td>';
content += '<td>' + id.email + '</td>';
content += '</tr>';
});

the main issue come from this line let mail = tabStudents.email; tabstudents is not define and in the process you try to do it's from the iterator of the foreach loop
in my sample i renamed it student
JSON.parse(data).forEach(student => {
let mail = student.email;
here the full sample
function displayPopup(data) {
if (data) { // si data n'est pas vide
let content = '';
let modal = document.getElementById("myModal");
let contentModal = document.getElementById("modal-body");
let span = document.getElementsByClassName("close")[0];
content += '<table class="table"><thead><tr><th>Nom</th><th>Prénom</th><th>Companie</th><th>Tags</th><th class="copy">Email</th></tr></thead><tbody>';
JSON.parse(data).forEach(student => {
let mail = student.email;
console.log(mail)
content += '<tr>';
content += '<td>' + student.lastname + '</td>';
content += '<td>' + student.firstname + '</td>';
content += '<td>' + student.company + '</td>';
content += '<td>' + student.tags + '</td>';
content += '<td>' + student.email + '</td>';
content += '</tr>';
});
content += '</tbody></table>';
contentModal.innerHTML = content;
modal.style.display = "block"
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
}
}
displayPopup('[{"id": 1, "email":"test#test.r"}]');
<div id="myModal">
<div id="modal-body">
<span class="close"></span>
</div>
</div>

Related

display realtime database from firebase to html table

when i display the table my web app display undefined can someone help me please [realtime database
var database = firebase.database().ref().child('contact-#bluejetengineering/blue_jet/DB object Sensor');
database.once('value', function(snapshot){
if(snapshot.exists()){
var content = '';
snapshot.forEach(function(data){
var Sensor_1 = data.val().Sensor_1;
var Sensor_2 = data.val().Sensor_2;
var Sensor_3 = data.val().Sensor_3;
var Sensor_4 = data.val().Sensor_4
//content += '<tr>';
content += '<td>' + Sensor_1 + '</td>'; //column1
content += '<td>' + Sensor_2 + '</td>';//column2
content += '<td>' + Sensor_3 + '</td>';//column3
content += '<td>' + Sensor_4 + '</td>';//column4
content += '</tr>';
});
$('#ex-table').append(content);
}
});
</script>

Appending to tbody not showing data in table

I am trying to append some data to a Datatables tbody. I do recieve the data when I console.log() the data, but the data does not show when I try to append it to my Datatable (The id of my table is 'example' btw). I do not know where to go in terms of debugging this as well.
asyncRequest.then((tracks) => {
var tableData = '';
// rows
for (track in tracks) {
tableData += '<tr>';
tableData += '<td>' + tracks[track]._id + '</td>';
tableData += '<td>' + tracks[track].Position + '</td>';
tableData += '<td>' + tracks[track].Track + '</td>';
tableData += '<td>' + tracks[track].Artist + '</td>';
tableData += '<td>' + tracks[track].Streams + '</td>';
tableData += '<td>' + tracks[track].Url + '</td>';
tableData += '<td>' + tracks[track].Date + '</td>';
tableData += '</tr>';
}
console.log(tableData);
$(document).ready(function () {
var table = $('#example').DataTable();
$(table).find('tbody').append(tableData);
});
});
</script>
tracks: [0 … 99]
0:
_id: "5e8d677a6e5216bc865e084a"
Position: 1
Track: "Dance Monkey"
Artist: "Tones And I"
Streams: 6155025
Url: "https://open.spotify.com/track/1rgnBhdG2JDFTbYkYRZAku"
Date: "1/1/20"
Can u try this one fisrt destroy then append then refresh it
and put your document ready out of request and initialize there
$(document).ready(function () {
var table = $('#example').DataTable();
});
then after u take data appen it destroy it and refresh it
asyncRequest.then((tracks) => {
var tableData = '';
// rows
for (track in tracks) {
tableData += '<tr>';
tableData += '<td>' + tracks[track]._id + '</td>';
tableData += '<td>' + tracks[track].Position + '</td>';
tableData += '<td>' + tracks[track].Track + '</td>';
tableData += '<td>' + tracks[track].Artist + '</td>';
tableData += '<td>' + tracks[track].Streams + '</td>';
tableData += '<td>' + tracks[track].Url + '</td>';
tableData += '<td>' + tracks[track].Date + '</td>';
tableData += '</tr>';
}
console.log(tableData);
$('#example').DataTable().destroy();
$('#example').find('tbody').append(str);
$('#example').DataTable().draw();
});

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++;
});
}

jquery how to add image in table TD near specified text

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>

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)
}

Categories