How to trigger any event for dynamic element? - javascript

I have this one:
function fillCard()
{
const persons = document.getElementsByClassName("fillCard");
if(persons !== null)
{
for (var i = 0; i < persons.length; i++)
{
persons[i].addEventListener("click", function(event){
event.preventDefault();
var getUrl = this.getAttribute("href");
var url = new URL(location.origin + getUrl);
var Id = url.searchParams.get("id");
fetch(getUrl + "&id=" + Id + "&do=fillCard")
.then(response => response.json())
.then(data => {
document.getElementById("frm-newCard-lastname").value = data[0];
document.getElementById("frm-newCard-firstname").value = data[1];
document.getElementById("frm-newCard-dateofbirth").value = data[2];
document.getElementById("frm-newCard-phone_number").value = data[3];
document.getElementsByName("identifier")[0].value = data[4];
});
});
}
}
}
The problem is - those elements with class name fillCard are created dynamically by AJAX. The event listener does not work then. How to trigger the event properly? Thank you in advance for help.

Solution:
function fillCard()
{
document.addEventListener("click", function(e){
if(!e.target.matches('.fillCard'))
return;
e.preventDefault();
var getUrl = e.target.getAttribute("href");
var url = new URL(location.origin + getUrl);
var Id = url.searchParams.get("id");
fetch(getUrl + "&id=" + Id + "&do=fillCard")
.then(response => response.json())
.then(data => {
document.getElementById("frm-newCard-lastname").value = data[0];
document.getElementById("frm-newCard-firstname").value = data[1];
document.getElementById("frm-newCard-dateofbirth").value = data[2];
document.getElementById("frm-newCard-phone_number").value = data[3];
document.getElementsByName("identifier")[0].value = data[4];
});
});
}

Related

How can I add the link to the image or ttitle?

I am trying to add the link on the image or title. when I click on the image/text it should take me to another page index.html.
How can I do that?
const apiUrl = 'https://api.themoviedb.org/3/discover/movie
sort_by=popularity.desc&api_key=04c35731a5ee918f014970082a0088b1&page=1;
const IMGPATH = "https://image.tmdb.org/t/p/w1280";
const SEARCHAPI = "https://api.themoviedb.org/3/search/movie?
&api_key=04c35731a5ee918f014970082a0088b1&query=";
const main = document.getElementById("main");
const form = document.getElementById("form");
const search = document.getElementById("search");
showMovies(apiUrl);
function showMovies(url){
fetch(url).then(res => res.json())
.then(function(data){
console.log(data.results);
data.results.forEach(element => {
const el = document.createElement('div');
const image = document.createElement('img');
const text = document.createElement('h2');
text.innerHTML = `${element.title}`;
image.src = IMGPATH + element.poster_path;
el.appendChild(image);
el.appendChild(text);
main.appendChild(el);
});
});
}
form.addEventListener("submit", (e) => {
e.preventDefault();
main.innerHTML = '';
const searchTerm = search.value;
if (searchTerm) {
showMovies(SEARCHAPI + searchTerm);
search.value = "";
}
});
Fixed your code, the tick was to add a element instead of with the desired href
const apiUrl =
"https://api.themoviedb.org/3/discover/moviesort_by=popularity.desc&api_key=04c35731a5ee918f014970082a0088b1&page=1";
const IMGPATH = "https://image.tmdb.org/t/p/w1280";
const SEARCHAPI =
"https://api.themoviedb.org/3/search/movie? &api_key=04c35731a5ee918f014970082a0088b1&query=";
const main = document.getElementById("main");
const form = document.getElementById("form");
const search = document.getElementById("search");
showMovies(apiUrl);
function showMovies(url) {
fetch(url)
.then((res) => res.json())
.then(function (data) {
console.log(data.results);
data.results.forEach((element) => {
el = document.createElement("a");
el.href = "https://example.com"
const image = document.createElement("img");
const text = document.createElement("h2");
text.innerHTML = `${element.title}`;
image.src = IMGPATH + element.poster_path;
el.appendChild(image);
el.appendChild(text);
main.appendChild(el);
});
});
}
form.addEventListener("submit", (e) => {
e.preventDefault();
main.innerHTML = "";
const searchTerm = search.value;
if (searchTerm) {
showMovies(SEARCHAPI + searchTerm);
search.value = "";
}
});

cannot access element within function in javascript custom object

When I run this code it generates the appropriate file upload ui and adds the event listener to the upload button. However the first line in the upload function throws an error - Cannot read property 'style' of undefined - for this.missingFile. What am I doing wrong here?
function FileUploader(props) {
var div = document.querySelector(props.element);
var uid = generateGuid();
var templateHtml = "<p><div id=\"dvMissingFile-" + uid + "\" class=\"missing-file\"> Please choose a file.</div><input type=\"file\" id=\"flUploadedFile-" + uid + "\" name=\"flUploadedFile-" + uid + "\"/></p><div class=\"dvProgressBar\" id=\"progress-" + uid + "\"><div></div></div>";
div.innerHTML = templateHtml;
this.uploadButton = document.querySelector(props.uploadButton);
this.fileInput = document.querySelector("#flUploadedFile-" + uid);
this.missingFile = document.querySelector("#dvMissingFile-" + uid);
this.progress = document.querySelector("#progress-" + uid);
this.url = props.postUrl;
this.upload = function() {
this.missingFile.style.display = "none";
if (this.fileInput.files.length === 0) {
this.missingFile.style.display = "";
}
else {
var file = this.fileInput.files[0];
var xhr = new XMLHttpRequest();
var pbar = document.querySelector("#progress-" + uid + ">div");
if (xhr.upload) {
// do upload
}
}
}
this.uploadButton.addEventListener("click", this.upload);
}
Usage example
<div id="dvUploader"></div>
<button type="button" id="btnUpload" class="btn btn-primary">Upload</button>
<script>
var uploader = new FileUploader({
element: "#dvUploader",
uploadButton: "#btnUpload",
postUrl: "myposturl"
});
</script>
One small update to your code can help:
this.upload = function() {
// ...
}.bind(this);

JS one of my functions does not seem to exist

I have a function :
var postBet = function(enemyID, ip_1, ip_2, playerID) {
$.post("save.php", {
enemyID: enemyID,
ip_1: ip_1,
ip_2: ip_2,
playerID: playerID
},
function(data, status) {
document.getElementById("saveWarningText").innerHTML = data;
$("#saveWarningText").fadeIn(100);
setTimeout(function() {
$("#saveWarningText").fadeOut(100);
}, 3000);
}
);
};
Unlike all of my other functions when I attempt to call it I get: Uncaught ReferenceError: postBet is not defined
Update
Full code:
var cors_api_url = 'https://cors-anywhere.herokuapp.com/';
var doCORSRequest = function(options, printResult) {
var x = new XMLHttpRequest();
x.open(options.method, cors_api_url + options.url);
x.onload = x.onerror = function() {
printResult(
(x.responseText || '')
);
};
if (/^POST/i.test(options.method)) {
x.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
x.send(options.data);
};
var playerIDs = [""];
var playerNames = [""];
var playerScores = [""];
var enemyIDs = [""];
var enemyNames = [""];
var enemyScores = [""];
var parser2 = new DOMParser();
var xmlDoc2;
var done1 = false;
var done2 = false;
var step1 = function() {
for (var i = 0; i < playerIDs.length; i++) {
var url2 = "http://www" + document.getElementById('extension').value + ".myfantasyleague.com/" + (new Date()).getFullYear() + "/export?TYPE=playerScores&L=" + document.getElementById('code').value + "&RULES&PLAYERS=";
url2 = url2 + playerIDs[i] + ",";
var out2 = "";
callback1(i, url2);
if (i >= playerIDs.length - 1) {
done1 = true;
}
}
for (var i = 0; i < enemyIDs.length; i++) {
var url2 = "http://www" + document.getElementById('extension').value + ".myfantasyleague.com/" + (new Date()).getFullYear() + "/export?TYPE=playerScores&L=" + document.getElementById('code').value + "&RULES&PLAYERS=";
url2 = url2 + enemyIDs[i] + ",";
var out2 = "";
callback2(i, url2);
if (i >= playerIDs.length - 1) {
done2 = true;
}
}
if (done1 && done2) {
step2();
}
};
var callback1 = function(i, url2) {
doCORSRequest({
method: this.id === 'post' ? 'POST' : 'GET',
url: url2,
}, function printResult(result) {
out2 = result;
xmlDoc2 = parser2.parseFromString(out2, "text/xml");
var temp = 0;
for (var j = 0; j < parseInt(xmlDoc2.getElementsByTagName('playerScore').length) - 1; j++) {
if (xmlDoc2.getElementsByTagName('playerScore')[j].getAttribute('score') !== "") {
temp = temp + parseInt(xmlDoc2.getElementsByTagName('playerScore')[j].getAttribute('score'));
}
playerScores[i] = temp;
}
});
};
var callback2 = function(i, url2) {
doCORSRequest({
method: this.id === 'post' ? 'POST' : 'GET',
url: url2,
}, function printResult(result) {
out2 = result;
xmlDoc2 = parser2.parseFromString(out2, "text/xml");
var temp = 0;
for (var j = 0; j < parseInt(xmlDoc2.getElementsByTagName('playerScore').length) - 1; j++) {
if (xmlDoc2.getElementsByTagName('playerScore')[j].getAttribute('score') !== "") {
temp = temp + parseInt(xmlDoc2.getElementsByTagName('playerScore')[j].getAttribute('score'));
}
enemyScores[i] = temp;
}
});
};
var step2 = function() {
for (var i = 0; i < playerIDs.length; i++) {
var url2 = "http://www" + document.getElementById('extension').value + ".myfantasyleague.com/" + (new Date()).getFullYear() + "/export?TYPE=players&PLAYERS=";
url2 = url2 + playerIDs[i];
callback3(i, url2);
}
for (var i = 0; i < enemyIDs.length; i++) {
var url2 = "http://www" + document.getElementById('extension').value + ".myfantasyleague.com/" + (new Date()).getFullYear() + "/export?TYPE=players&PLAYERS=";
url2 = url2 + enemyIDs[i];
callback4(i, url2);
}
};
var callback3 = function(i, url2) {
doCORSRequest({
method: this.id === 'post' ? 'POST' : 'GET',
url: url2
}, function printResult(result) {
xmlDoc2 = parser2.parseFromString(result, "text/xml");
playerNames[i] = xmlDoc2.getElementsByTagName('player')[0].getAttribute('name');
var option = document.createElement("option");
var node = document.createTextNode(playerNames[i] + " : " + playerScores[i]);
option.appendChild(node);
var element = document.getElementById("you");
element.appendChild(option);
});
};
var callback4 = function(i, url2) {
doCORSRequest({
method: this.id === 'post' ? 'POST' : 'GET',
url: url2
}, function printResult(result) {
xmlDoc2 = parser2.parseFromString(result, "text/xml");
enemyNames[i] = xmlDoc2.getElementsByTagName('player')[0].getAttribute('name');
var option = document.createElement("option");
var node = document.createTextNode(enemyNames[i] + " : " + enemyScores[i]);
option.appendChild(node);
var element = document.getElementById("enemy");
element.appendChild(option);
});
};
var postBet = function(enemyID, ip_1, ip_2, playerID) {
$.post("save.php", {
enemyID: enemyID,
ip_1: ip_1,
ip_2: ip_2,
playerID: playerID
},
function(data, status) {
document.getElementById("saveWarningText").innerHTML = data;
$("#saveWarningText").fadeIn(100);
setTimeout(function() {
$("#saveWarningText").fadeOut(100);
}, 3000);
}
);
};
(function() {
postBet('1', '1', '1', '1');
document.getElementById('start').onclick = function(e) {
var url = "http://www" + document.getElementById('extension').value + ".myfantasyleague.com/" + (new Date()).getFullYear() + "/export?TYPE=rosters&L=" + document.getElementById('code').value;
var data = "";
var output = "";
var parser = new DOMParser();
var xmlDoc;
var n1 = document.getElementById("you");
while (n1.firstChild) {
n1.removeChild(n1.firstChild);
}
var n2 = document.getElementById("enemy");
while (n2.firstChild) {
n2.removeChild(n2.firstChild);
}
e.preventDefault();
doCORSRequest({
method: this.id === 'post' ? 'POST' : 'GET',
url: url,
data: data
}, function printResult(result) {
output = result;
xmlDoc = parser.parseFromString(output, "text/xml");
for (var i = 1; i < xmlDoc.getElementsByTagName("franchise")[parseInt(document.getElementById('team').value) - 1].childNodes.length; i += 2) {
playerIDs.length = Math.round((xmlDoc.getElementsByTagName("franchise")[parseInt(document.getElementById('team').value) - 1].childNodes.length / 2) - 1);
playerScores.length = Math.round((xmlDoc.getElementsByTagName("franchise")[parseInt(document.getElementById('team').value) - 1].childNodes.length / 2) - 1);
playerIDs[Math.round(i / 2) - 1] = xmlDoc.getElementsByTagName("franchise")[parseInt(document.getElementById('team').value) - 1].childNodes[i].getAttribute('id');
}
for (var i = 1; i < xmlDoc.getElementsByTagName("franchise")[parseInt(document.getElementById('other').value) - 1].childNodes.length; i += 2) {
enemyIDs.length = Math.round((xmlDoc.getElementsByTagName("franchise")[parseInt(document.getElementById('other').value) - 1].childNodes.length / 2) - 1);
enemyIDs[Math.round(i / 2) - 1] = xmlDoc.getElementsByTagName("franchise")[parseInt(document.getElementById('other').value) - 1].childNodes[i].getAttribute('id');
}
step1();
});
};
})();
Turns out 000webhost was using a cached version of the website. It was using an older version of my code without that function. Fixed the problem by deleting and re-uploading my code to 000webhost.

Javascript - FileReader how can I read and process each file at a time among multiple files

I am trying let the user drop multiple excel file and extract desired values from each one of the files and upload it to website ONE FILE AT A TIME.
My code is not working, and I am assuming this is because of the callback problem..
Could anybody help?
Edit: I also added my uploadFile function. I very much appreciate your help.
for(var i = 0; i < fileList.length; i++) {
//console.log(fileList[i]["file"]);
var reader = new FileReader();
var f = fileList[i]["file"];
//var fName = fileList[i]["fileName"];
var excelObject = fileList[i];
reader.onload = function(ev) {
var data = ev.target.result;
if(!rABS) data = new Uint8Array(data);
var wb = XLSX.read(data, {type: rABS ? 'binary' : 'array'});
var einAddress = "B3";
var engCodeAddress = "B1";
var goAddress = "B2";
var errMsg = tabName + " tab or required value is missing";
// Worksheet with the necessary info
try{
var ws = wb.Sheets[tabName];
var ein_cell = ws[einAddress];
ein = (ein_cell ? ein_cell.v.toString() : undefined);
var eng_cell = ws[engCodeAddress];
engCode = (eng_cell ? eng_cell.v.toString() : undefined);
var go_cell = ws[goAddress];
goLocator = (go_cell ? go_cell.v.toString() : undefined);
if(ein == undefined || engCode == undefined || goLocator == undefined){
hasValues = false;
}
excelObject["EngagementCode"] = engCode;
excelObject["GoSystem"] = goLocator;
excelObject["EIN"] = ein;
if(hasValues && isValid){
uploadFile(fileList[i], userInfo);
} else {
noValueErrorHandler(errMsg);
}
} catch(err){
hasValues = false;
}
};
if(rABS) reader.readAsBinaryString(f); else reader.readAsArrayBuffer(f);
}
function uploadFile(f, userInfo) {
// Define the folder path for this example.
var serverRelativeUrlToFolder = listName;
// Get info of the file to be uploaded
var file = f;
var fileInput = file["file"];
var newName = file["fileName"];
var ein = file["EIN"];
var engCode = file["EngagementCode"];
var email = userInfo;
var goLocator = file["GoSystem"];
console.log("file: " + file);
// Get the server URL.
var serverUrl = _spPageContextInfo.siteAbsoluteUrl + "/StatusTracker";
// Initiate method calls using jQuery promises.
// Get the local file as an array buffer.
var getFile = getFileBuffer(fileInput);
getFile.done(function (arrayBuffer) {
// Add the file to the SharePoint folder.
var addFile = addFileToFolder(arrayBuffer, newName);
addFile.done(function (file, status, xhr) {
// Get the list item that corresponds to the uploaded file.
var getItem = getListItem(file.d.ListItemAllFields.__deferred.uri);
getItem.done(function (listItem, status, xhr) {
// Change the display name and title of the list item.
var changeItem = updateListItem(listItem.d.__metadata);
changeItem.done(function (data, status, xhr) {
processedCount += 1;
if (processedCount < fileCount) {
uploadFile(fileList[processedCount], email);
} else if (processedCount == fileCount){
$("#dropbox").text("Done, drop your next file");
$("#ADMNGrid").data("kendoGrid").dataSource.read();
fileList = [];
alert("Total of " + processedCount + " items are processed!");
}
// Refresh kendo grid and change back the message and empty fileList
//$("#dropbox").text("Drag your Fund/Lower Tier workpaper here ...");
//location.reload(true);
});
changeItem.fail(onError);
});
getItem.fail(onError);
});
addFile.fail(onError);
});
getFile.fail(onError);
You might put the whole thing into an async function and await a Promise for each iteration, forcing the files to be processed in serial. You didn't post your uploadFile, but if you have it return a Promise that resolves once it's done, you could do the following:
async fn() {
for (var i = 0; i < fileList.length; i++) {
await new Promise((resolve, reject) => {
//console.log(fileList[i]["file"]);
var reader = new FileReader();
var f = fileList[i]["file"];
//var fName = fileList[i]["fileName"];
var excelObject = fileList[i];
reader.onload = function(ev) {
var data = ev.target.result;
if (!rABS) data = new Uint8Array(data);
var wb = XLSX.read(data, {
type: rABS ? 'binary' : 'array'
});
var einAddress = "B3";
var engCodeAddress = "B1";
var goAddress = "B2";
var errMsg = tabName + " tab or required value is missing";
// Worksheet with the necessary info
try {
var ws = wb.Sheets[tabName];
var ein_cell = ws[einAddress];
ein = (ein_cell ? ein_cell.v.toString() : undefined);
var eng_cell = ws[engCodeAddress];
engCode = (eng_cell ? eng_cell.v.toString() : undefined);
var go_cell = ws[goAddress];
goLocator = (go_cell ? go_cell.v.toString() : undefined);
if (ein == undefined || engCode == undefined || goLocator == undefined) {
hasValues = false;
}
excelObject["EngagementCode"] = engCode;
excelObject["GoSystem"] = goLocator;
excelObject["EIN"] = ein;
if (hasValues && isValid) {
uploadFile(fileList[i], userInfo)
.then(resolve);
} else {
noValueErrorHandler(errMsg);
reject();
}
} catch (err) {
hasValues = false;
reject();
}
};
if (rABS) reader.readAsBinaryString(f);
else reader.readAsArrayBuffer(f);
});
}
}

Change Fetch URL from event listener?

I'm trying to change a global variable from inside a click event listener. However the variable fails to change once button is clicked. The objective here is to change a URL for a fetch request.
// Default URL
var url = 'https://newsapi.org/v2/top-headlines?sources=bbc-news&Apikey123';
var req = new Request(url);
// Event Listener - Change URL
document.getElementById('btn').addEventListener('click', function() {
var url = 'https://newsapi.org/v2/top-headlines?sources=cnn&apiKey=Apikey123';
var req = new Request(url);
sendRequest();
})
// Fetch Data from API
function sendRequest() {
fetch(req)
.then(r => r.json())
.then(r => {
const container = document.getElementsByClassName('post-container')[0];
for(i = 0; i < 5 ; i++) {
// Create post elements
const post = document.createElement('div');
const postHeader = document.createElement('div');
const postBody = document.createElement('div');
// Set ID
post.id = 'post';
postHeader.id = 'post-header';
postBody.id = 'post-body';
// Append Elements
container.appendChild(post);
post.appendChild(postHeader);
post.appendChild(postBody);
// Post title data from array into div
let article = r.articles[i];
let title = article.title;
let content = article.description;
postHeader.innerHTML = title;
postBody.innerHTML = content;
}
console.log(container);
});
}
sendRequest();
To solve the problem:
...
document.getElementById('btn').addEventListener('click', function() {
var url = 'https://newsapi.org/v2/top-headlines?sources=cnn&apiKey=Apikey123';
// Don't use var, becouse it's variable have scope in current function
// var req = new Request(url);
req = new Request(url);
sendRequest();
})
...
But better send param to sendRequest:
...
// Event Listener - Change URL
document.getElementById('btn').addEventListener('click', function() {
var url = 'https://newsapi.org/v2/top-headlines?sources=cnn&apiKey=Apikey123';
var req = new Request(url);
sendRequest(req); // <--- set param
})
// Fetch Data from API
function sendRequest(req) { // <--- get param
...
});
...
Remove the var from inside the Event Listener
document.getElementById('btn').addEventListener('click', function()
{
url = 'https://newsapi.org/v2/top-headlines?sources=cnn&apiKey=Apikey123';
var req = new Request(url);
sendRequest();
})
The thing is you are declaring the var url twice , and var req twice
the first one at the begining of your code and the second one in your event listner ,
try this
var url = 'https://newsapi.org/v2/top-headlines?sources=bbc-news&Apikey123';
var req = new Request(url);
// Event Listener - Change URL
document.getElementById('btn').addEventListener('click', function() {
url = 'https://newsapi.org/v2/top-headlines?sources=cnn&apiKey=Apikey123';
req = new Request(url);
sendRequest();
})
// Fetch Data from API
function sendRequest() {
fetch(req)
.then(r => r.json())
.then(r => {
const container = document.getElementsByClassName('post-container')[0];
for(i = 0; i < 5 ; i++) {
// Create post elements
const post = document.createElement('div');
const postHeader = document.createElement('div');
const postBody = document.createElement('div');
// Set ID
post.id = 'post';
postHeader.id = 'post-header';
postBody.id = 'post-body';
// Append Elements
container.appendChild(post);
post.appendChild(postHeader);
post.appendChild(postBody);
// Post title data from array into div
let article = r.articles[i];
let title = article.title;
let content = article.description;
postHeader.innerHTML = title;
postBody.innerHTML = content;
}
console.log(container);
});
}
sendRequest();

Categories