Need help referencing elements - javascript

I know I'm asking really simple questions but I'm a beginner and it the process of learning. I've got this code but I don know how to make it work. The output i expect is upon clicking the button it activates function insertAfter and adds text/paragraph that ill write.
I've tried: onclick='insertAfter(test,index.this)'
It didn't work and consoled said it was undefined.
var content = "";
Applications.forEach(generatetable);
function testfn(index, tdElement) {
console.log(tdElement.parentElement);
console.log(index);
console.log(Applications[index].Name);
}
function generatetable(item, index, arrays) {
var columns = "";
columns = columns + "<td onclick='testfn(\"" + index + "\", this)'>" + "<button onclick='insertAfter(test?,???)' type=\"button\">Click Me!</button>" + item.UAID + "</td>";
columns = columns + "<td>" + item.Name + "</td>";
columns = columns + "<td>" + "<a href='www.wahtever.com'>map</a>" + "</td>";
content = content + "<tr>" + columns + "</tr>";
}
var test = "<tr><td>fsdf</td></tr>";
document.getElementById("table").innerHTML = content;
function insertAfter(newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
It is supposed to insert a paragraph preferably what i put in the test variable but if there is better is better solution please let me know.

<button onclick='insertAfter(test,ElementID)>
The second refference node (ElementID) should be be the id of the element after which it is to be put. So it has to be somehow refferenced for example by id.

Related

Invoking a function multiple times but losing past data

Simply working on a homework assignment, at the end, just need to display this method 5 times. Issue is as title states once I invoke the function the next invoke overwrites past invoke.
Heres what I am currently doing.
<p id="table">
<script type="text/javascript">
showResults(race[0], name1, party1, votes1);
showResults(race[1], name2, party2, votes2);
showResults(race[2], name3, party3, votes3);
showResults(race[3], name4, party4, votes4);
showResults(race[4], name5, party5, votes5);
</script>
</p>
I have used a debugger to try and find a fix, browsed the internet for about an hour now, tried to use a .call but couldn't quite get that working either and I know document.write isn't a viable option because it rewrites everything.
Any help or useful links on the issue would be really appreciated!
Here is the showresults function
function showResults(race, name, party, votes)
{
var totalV = totalVotes(votes);
var result = "";
result += "<h2>" + race + "</h2>";
result += "<table cellspacing = '0'>";
result += "<tr>";
result += "<th>Candidate</th>"
result += "<th class='num'>Votes</th>";
result += "<th class='num'>%</th>";
result += "</tr>";
for (var i = 0; i < name.length; i++)
{
result += "<tr>";
result += "<td>" + name[i] + '(' + party[i] + ')' + "</td>";
result += "<td class='num'>" + votes[i] + "</td>";
var percent = calcPercent(votes[i], totalV)
result += "<td class='num'>(" + percent + "%)</td>";
result += createBar(party[i], percent);
result += "</tr>";
}
result += "</table>";
document.getElementById("table").innerHTML = result;
}
The Statement
document.getElementById("table").innerHTML = result;
Sets the innerHTML of your "table" element, thus overwriting it each time you set it.
try to
append(result);
to a existing DOM node so your result gets appended to the document.

Calling a function in dynamically created button javascript

I'm trying to create a button with a an onClick that calls a function with the signature deleteEntry(entry). However, I get an error saying that entry is undefined even though I am using it in the same function. I tried adding escape characters but it does not have any effect. Any ideas?
function addToTable(entry) {
var result = "<tr>"
result += "<td>" + entry.id + "</td>";
result += "<td>" + entry.title + "</td>";
result += "<td>" + entry.url + "</td>";
result += "<td><button class=\"btn\" onClick=\"deleteEntry(" + entry +
")\">Delete</button></td>";
result += "</tr>";
$("#table").append(result);
}
You can create the button as a jQuery object and use the on method to listen to the click event. Then when the event listener is attached append the button to the row like the other elements in the function.
Check the code snippet below to see it in action.
// Dummy entry.
var entry = {
id: 0,
title: 'test',
url: 'http://url.com'
}
// Your AJAX call.
function deleteEntry(entry) {
console.log(entry);
}
function addEntryToTable(entry) {
var $id = $('<td>' + entry.id + '</td>');
var $title = $('<td>' + entry.title + '</td>');
var $url = $('<td>' + entry.url + '</td>');
var $button = $('<button class="btn">Delete</button>');
var $buttonWrap = $('<td></td>');
var $row = $('<tr></tr>');
// Add 'click' event listener to the button.
$button.on('click', function(event) {
deleteEntry(entry);
});
$buttonWrap.append($button)
$row.append($id, $title, $url, $buttonWrap);
$('#table').append($row);
}
addEntryToTable(entry);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table"></table>
If you inspect this button you generated it will probably have the following attribute: onClick="deleteEntry([object Object])
I think what you want is:
result += "<td><button class=\"btn\" onClick=\"deleteEntry(" + entry.id + ")\">Delete</button></td>";
I guess you have a list variable "entries" somewhere.
In the delete function you can find the clicked entry with the inputed Id.

Javascript syntax for concatenating in URL

I can show orderB.id as table data. I want to use this value in the href, but I am struggling with syntax.
var output = results.reduce(function (orderA, orderB){
var row = "<tr>";
row += "<td>" + orderB.name + "</td>";
row += "<td>" + orderB.type + "</td>";
row += "<td>" + orderB.id + "</td>";
row += "<td><a href='/update/' + orderB.id + >Update</a></td>";
return orderA + row;
},"")
I have tried:
row += "<td><a href='/update/' + orderB.id + >Update</a></td>";
row += "<td><a href='/update/' + 'orderB.id' + >Update</a></td>";
row += "<td><a href='/update/orderB.id' + >Update</a></td>";
These output:
/update/
/update/
/update/orderB.id
I want for example: /update/3
use template literals :
row += `<td>Update</td>`;
or simply concat your variables with the htmml string like :
row += '<td>Update</td>';
As has been suggested, template literals are a good way to go, but you have to be careful about just sticking strings together to create HTML -- if there are characters like <, >, or & there can be problems. I'd use Lodash and modify the answer given by another poster like this:
row += `<td>Update</td>`;

Dynamically Create HTML Table with Pagination

I'm trying to create an html table with pagination. I'm requesting JSON data via $.get call using JQuery which is an async call. The solution I currently have duplicates the HTML code whenever a new page is selected. I know this is an asynchronocity but I'm not exactly sure what the best method to overcome this would be.
<script type="text/javascript">
function generateTable(currentPage) {
this.URL = "https://jsonplaceholder.typicode.com/posts";
$.getJSON(URL, function(data) {
const pages = Math.ceil(data.length / 10);
for(let i = currentPage*10; i<(currentPage*10)+10; i++ ) {
let post = data[i];
let tblRow = "<tr>" + "<td>" + post.userId + "</td>" + "<td>" + post.id + "</td>" + "<td>" + post.title + "</td>" + "<td>" + post.body + "</td>" + "</tr>"
$(tblRow).appendTo("#jsonData tbody");
}
for (let i = 1; i <= pages; i++) {
let pagingHtml = "<a href=# onclick=generateTable("+(i-1)+")>"+" "+i+" "+"</a>"
$(pagingHtml).appendTo("#paging");
}
})
}
generateTable(0);
</script>
Before populating the HTML, clear out the current rows from the page:
$("#jsonData tbody,#paging").empty();
This assumes that those two parent elements only have dynamic content. If not, you should reference container elements that only have dynamic content (so no headers, footers, ...etc).

how to store array data in table?

I wanted the user to enter any alphabet in a text field, when he/she clicks on the Find! button, it will go through my php file and find a list of words that start with that alphabet (of course it's only a limited amount of words). And I want to output it to a table, with 5 columns, each cell containing one word.
Something like this:
in my HTML:
<label>
Enter any alphabet:
<input name="alphabet" type="text" id="alphabet"></label>
<input type="button" value="Find!" id="goFind">
<table border="1" id="output">
</table>
and Javascript:
$(document).ready(function () {
$.ajaxSetup({
cache: false
});
var bunchOfWords = function (data) {
var listOfWords = "";
if(!Array.isArray(data)) {
return false;
}
else {
for(i = 0; i < data.length; i = +5) {
listOfWords += "<tr><td>" + data[i] + "</td>" +
"<td>" + data[i] + "</td>" +
"<td>" + data[i] + "</td>" +
"<td>" + data[i] + "</td>" +
"<td>" + data[i] + "</td></tr>";
}
}
};
$("#goFind").click(function () {
var theWord = $("#alphabet").val();
$("#output").html("Loading..."); //gives the user an indication that it's loading
$.getJSON("wordslookup.php", "startswith=" + theWord, listOfWords);
});
});
Can't seem to figure out what's wrong.
listOfWords is out of scope in $.getJSON also its not a function, you should pass bunchOfWords to $.getJSON instead. To put the data in the table simply replace the current inner html, $("#output").html(listOfWords);

Categories

Resources