Binding eventhandlers in a for-loop - javascript

I am creating html-elements in a loop, and want to attach event-handlers to some of the elements. This handlers need to know the id of the element that fired the event, so I added the elements id's as a parameter of the binded function, but anyway what element I click at the end, the function always received the id of the last element, not of the element that I clicked.
Here is the code (more simplified version in the next code-block) (I'm using jQuery, but this is not a jQuery-problem, just a JavaScript-problem)
receiveObjects = function (JSONobj, StatusString, jqXHR) {
var html, i, el;
// error-handling is not shown here
html = '<table>';
for (i = 0; i < JSONobj.list.length; i++) {
el = JSONobj.list[i];
html += '<tr>';
html += '<td class="td1" id="td1'+el.itemID+'">';
html += '<table>';
html += '<tr>';
html += '<td><img id="up9x'+el.itemID+'" src="pics/arrowUp9.png" alt="" style="width:25px;height:66px;"></td>';
html += '<td><img id="up3x'+el.itemID+'" src="pics/arrowUp3.png" alt="" style="width:25px;height:66px;"></td>';
html += '<td><img id="up1x'+el.itemID+'" src="pics/arrowUp1.png" alt="" style="width:25px;height:66px;"></td>';
html += '</tr>';
html += '<tr>';
html += '<td><img id="down9x'+el.itemID+'" src="pics/arrowDown9.png" alt="" style="width:25px;height:66px;"></td>';
html += '<td><img id="down3x'+el.itemID+'" src="pics/arrowDown3.png" alt="" style="width:25px;height:66px;"></td>';
html += '<td><img id="down1x'+el.itemID+'" src="pics/arrowDown1.png" alt="" style="width:25px;height:66px;"></td>';
html += '</tr>';
html += '<tr>';
html += '<td colspan="3">';
html += '<div><button id="delete'+el.itemID+'" name="delete'+el.itemID+'" value="delete'+el.itemID+'">delete</button></div>';
html += '<div id="saveDiv'+el.itemID+'" style="display:none;">';
html += '<button id="save'+el.itemID+'" name="save'+el.itemID+'" value="save'+el.itemID+'">save</button>';
html += '</div>';
html += '</td>';
html += '</tr>';
html += '</table>';
html += '</td>';
html += '<td class="td2" id="td2'+el.itemID+'">';
html += '<table>';
html += '<tr>';
html += '<td>Titel </td>';
html += '<td>';
html += '<input class="grau" type="text" id="inTitel'+el.itemID+'" size="30" maxsize="50" value="'+el.Titel+'">';
html += '</td>';
html += '</tr>';
html += '<tr>';
html += '<td>ET</td>';
html += '<td>';
html += '<input class="grau" type="text" id="inET'+el.itemID+'" size="20" maxsize="30" value="'+el.ET+'">';
html += '</td>';
html += '</tr>';
html += '<tr>';
html += '<td>Text </td>';
html += '<td>';
html += '<textarea class="grau" id="inText'+el.itemID+'" rows="4" cols="30">'+el.Text+'</textarea>';
html += '</td>';
html += '</tr>';
html += '</table>';
html += '<button id="loadPdf'+el.itemID+'" name="loadPdf'+el.itemID+'" value="loadPdf'+el.itemID+'">upload pdf</button>';
html += '</td>';
html += '<td class="td3" id="td3'+el.itemID+'">';
html += '<img src="'+el.pic+'">';
html += '<div>';
html += '<button id="newPic'+el.itemID+'" name="newPic'+el.itemID+'" value="newPic'+el.itemID+'">create pic from pdf</button> ';
html += '</div>';
html += '</td>';
html += '</tr>';
}
html += '</table><div class="ErrorMsg" id="changeRedError"></div>';
$('#workBlock').html(html);
//after the elements are inserted into the dom, the eventhandlers should be binded:
for (i = 0; i < JSONobj.list.length; i++) {
el = JSONobj.list[i];
$('#up9x'+el.itemID).on('click',function(){evHd.clickMove(el.itemID,-9);})
$('#up3x'+el.itemID).on('click',function(){evHd.clickMove(el.itemID,-3);})
$('#up1x'+el.itemID).on('click',function(){evHd.clickMove(el.itemID,-1);})
$('#down9x'+el.itemID).on('click',function(){evHd.clickMove(el.itemID,9);})
$('#down3x'+el.itemID).on('click',function(){evHd.clickMove(el.itemID,3);})
$('#down1x'+el.itemID).on('click',function(){evHd.clickMove(el.itemID,1);})
$('#delete'+el.itemID).on('click',function(){evHd.clickDelete(el.itemID);})
$('#save'+el.itemID).on('click',function(){evHd.clickSave(el.itemID);})
$('#inTitel'+el.itemID).on('change keyup paste mouseup',function(){evHd.changed(el.itemID);})
$('#inET'+el.itemID).on('change keyup paste mouseup',function(){evHd.changed(el.itemID);})
$('#inText'+el.itemID).on('change keyup paste mouseup',function(){evHd.changed(el.itemID);})
$('#loadPdf'+el.itemID).on('click',function(){evHd.clickLoadPdf(el.itemID);})
$('#newPic'+el.itemID).on('click',function(){evHd.clickNewPic(el.itemID);})
}
}
The problem must be located in the way how I attach the id (el.itemID) to the event-handler function. Simplified:
for (i = 0; i < 500; i++) {
el = JSONobj.list[i];
$('#prefix'+i).on('click',function(){
handler(i); //this seems to be problematic
})
}
I think I know where the problem is, but I have no idea how to solve it. Can you help, please?

This is a very common mistake, due to JavaScript's concept of closures (function plus pointers to all the variables outside the function that have been referenced in the function body). You can solve this with an IIFE (immediately invoked function expression):
for (i = 0; i < 500; i++) {
(function(num) {
$('#prefix' + num).on('click',function() {
handler(num);
})
})(i);
}
This immediately invoked function will create a new scope and thus have the correct i saved in num. Otherwise, JavaScript's closure (the function keeps a pointer on i and thus always references 500 after the for loop ended) will mess with your event handlers.

Related

Downloading CSV contents via Ajax and PHP

I am trying to download CSV contents via PHP script hosted on the server.
This is the jquery code that executes and creates a table:
$(document).ready(function() {
$("#btnSubmit").click(function(){
$.ajax({
type: 'GET',
url: 'http://mydomaincom/wp-content/uploads/get-csv.php',
data: null,
success: function(text) {
var fields = text.split(/\n/);
fields.pop(fields.length-1);
var headers = fields[0].split(','),
html = '<table>';
html += '<tr>';
for(var i = 0; i < headers.length; i += 1) {
html += '<th scope="col">' + headers[i] + '</th>';
}
html += '</tr>';
var data = fields.slice(1, fields.length);
for(var j = 0; j < data.length; j += 1) {
var dataFields = data[j].split(',');
html += '<tr>';
html += '<td>' + dataFields[0] + '</td>';
html += '<td>' + dataFields[1] + '</td>';
html += '<td>' + dataFields[2] + '</td>';
html += '</tr>';
}
html += '</table>';
$(html).appendTo('body');
}
});
});
});
Contents of get-csv.php file:
<?php
header('Content-Type: text/plain');
$csv = file_get_contents('http://mydomaincom/wp-content/uploads/csv-samples.csv');
echo $csv;
?>
Here is the code for button:
<!-- Begin Button -->
<div class="demo">
<input id = "btnSubmit" type="submit" value="Get It"/>
</div>
<!-- End Button -->
From browser:
I can access http://mydomaincom/wp-content/uploads/get-csv.php - no issues
I can access http://mysitecom/wp-content/uploads/csv-samples.csv - no issues
When I click on button nothing happens.
Thanks
Below I tried to put together a working snippet where you can possibly see how it works when it works ...
$(document).ready(function () {
$("#btnSubmit").click(function () {
$.ajax({
type: 'GET',
// url: 'http://mydomaincom/wp-content/uploads/get-csv.php',
// url: 'https://jsonplaceholder.typicode.com/users', // --> JSON
url: "https://data.cdc.gov/api/views/45um-c62r/rows.csv",
data: null,
success: function (text) {
var fields = text.split(/\n/);
fields.pop(fields.length - 1);
var headers = fields[0].split(','), html = '<table>';
html += '<tr>';
for (var i = 0; i < (headers.length,3); i += 1) {
html += '<th scope="col">' + headers[i] + '</th>';
}
html += '</tr>';
var data = fields.slice(1, fields.length);
for (var j = 0; j < data.length; j += 1) {
var dataFields = data[j].split(',');
html += '<tr>';
html += '<td>' + dataFields[0] + '</td>';
html += '<td>' + dataFields[1] + '</td>';
html += '<td>' + dataFields[2] + '</td>';
html += '</tr>';
}
html += '</table>';
$(html).appendTo('body');
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btnSubmit">get data</button>
After looking around a bit further I did actually find some publicly available CSV data ("Rates of TBI-related Emergency Department Visits, Hospitalizations, and Deaths - United States, 2001 – 2010" from the U.S. Department of Health & Human Services) and I am now using that to demonstrate the AJAX process.
So, your code basically works. It could be simplified of course but that is not the point. I guess that the problems you encounter with your site are probably CORS-related.

How to insert link in to html href tag

im curently working on a script that pulls data from google sheets and transforms it in to a html table. but i have links in my google sheets tabele so i want that these links get but in a button that looks nice but icant figure out how to do that.
i curently have this loob
for (var i = 0; i < entry.length; i++) {
html += '<tr>';
html += '<td>' + entry[i]['gsx$komponente']['$t'] + '</td>';
html += '<td>' + entry[i]['gsx$name']['$t'] + '</td>';
html += '<td>' + entry[i]['gsx$hersteller']['$t'] + '</td>';
html += '<td>' + entry[i]['gsx$preis']['$t'] + '</td>';
html += '<td>' + entry[i]['gsx$link']['$t'] + '</td>';
html += '</tr>';
}
html += '</table>';
the entry[i]['gsx$link']['$t'] gets me the links i just cant get it to work inside a button
if you have any idea how i can solve this problem please help me
here is the Complete code
<!DOCTYPE html>
<meta charset="ISO-8859-1">
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
// ID of the Google Spreadsheet
var spreadsheetID = "1Xx0qGY_5Ic1KNB7m8Lu5mZqHE4XQzauvcugTVUGwgqk";
// Make sure it is public or set to Anyone with link can view
var url = "https://spreadsheets.google.com/feeds/list/" + spreadsheetID + "/od6/public/values?alt=json";
// make JSON call to Google Data API
$.getJSON(url, function(data) {
// set global html variable
var html = '';
// build table headings
html += '<table>';
html += '<tr>';
html += '<th>Komponente</th>';
html += '<th>Name</th>';
html += '<th>Hersteller</th>';
html += '<th>Preis</th>';
html += '<th>Link</th>';
html += '</tr>';
// loop to build html output for each row
var entry = data.feed.entry;
/**
** Change to descending order
** for (var i = entry.length - 1; i >= 0; i -= 1) {
*/
for (var i = 0; i < entry.length; i++) {
html += '<tr>';
html += '<td>' + entry[i]['gsx$komponente']['$t'] + '</td>';
html += '<td>' + entry[i]['gsx$name']['$t'] + '</td>';
html += '<td>' + entry[i]['gsx$hersteller']['$t'] + '</td>';
html += '<td>' + entry[i]['gsx$preis']['$t'] + '</td>';
html += '<td>' + entry[i]['gsx$link']['$t'] + '</td>';
html += '</tr>';
}
html += '</table>';
// output html
$('.console').html(html);
});
// loading animation
var loading = $('.loading');
loading.hide();
$(document)
.ajaxStart(function() {
loading.show();
})
.ajaxStop(function() {
loading.hide();
});
</script>
<div class="console"></div>
<div class="loading">
</div>
</body>
</html>
You just need to wrap the link inside <a> tag
for (var i = 0; i < entry.length; i++) {
html += '<tr>';
html += '<td>' + entry[i]['gsx$komponente']['$t'] + '</td>';
html += '<td>' + entry[i]['gsx$name']['$t'] + '</td>';
html += '<td>' + entry[i]['gsx$hersteller']['$t'] + '</td>';
html += '<td>' + entry[i]['gsx$preis']['$t'] + '</td>';
html += '<td><a href=' + entry[i]['gsx$link']['$t'] + '>' +entry[i]['gsx$link']['$t'] + '</a></td>';
html += '</tr>';
}

Html javascript row instead of col

I have this script, but i'd like to be able to display 2 rows / 7 cols instead of 7 rows / 2 cols.
<script type="text/javascript">
var date = new Date(); // today
var times = prayTimes.getTimes(date, [48.23, 4.28], 2);
var list = ['Fajr', 'Sunrise', 'Dhuhr', 'Asr', 'Maghrib', 'Isha'];
var html = '<table id="timetable">';
html += '<tr><td colspan="7">'+ date.toLocaleDateString()+ '</td></tr>';
for(var i in list) {
html += '<tr><td>'+ list[i]+ '</td>';
html += '<td>'+ times[list[i].toLowerCase()]+ '</td></tr>';
}
html += '</table>';
document.getElementById('table').innerHTML = html;
</script>
Use separate loops to create each row, first iterating and printing the items from the list, then the corresponding times.
var date = new Date(); // today
var times = prayTimes.getTimes(date, [48.23, 4.28], 2);
var list = ['Fajr', 'Sunrise', 'Dhuhr', 'Asr', 'Maghrib', 'Isha'];
var html = '<table id="timetable">';
html += '<tr><td colspan="7">'+ date.toLocaleDateString()+ '</td></tr>';
html += '<tr>';
for(var i in list) {
html += '<td>'+ list[i]+ '</td>';
}
html += "</tr>";
html += "<tr>";
for (var i in list) {
html += '<td>'+ times[list[i].toLowerCase()]+ '</td></tr>';
}
html += '</tr></table>';
document.getElementById('table').innerHTML = html;
Here's my solution
2 rows with the first row showing list[i] and the second row showing times[list[i].toLowerCase()]
<script type="text/javascript">
var date = new Date(); // today
var times = prayTimes.getTimes(date, [48.23, 4.28], 2);
var list = ['Fajr', 'Sunrise', 'Dhuhr', 'Asr', 'Maghrib', 'Isha'];
var html = '<table id="timetable">';
html += '<tr><td colspan="7">'+ date.toLocaleDateString()+ '</td></tr>';
html += '<tr>';
for(var i in list) {
html += '<td>'+ list[i]+ '</td>';
}
html += '</tr>';
html += '<tr>';
for(var i in list) {
html += '<td>'+ times[list[i].toLowerCase()]+ '</td>';
}
html += '</tr>';
html += '</table>';
document.getElementById('table').innerHTML = html;

Remove last TD before append the element

I have this jQuery code:
html += '<tr>';
html += '<td>AAA</td>';
html += '<td>BBB</td>';
html += '<td>CCC</td>';
html += '<td>DDD</td>';
html += '<td>EEE</td>';
html += '<td>FFF</td>';
html += '</tr>';
$(html).appendTo("#fabricanteBody");
$(html).appendTo("#selFabricanteBody");
How do I remove the last td (html += '<td>FFF</td>') element on the html var before append it to #selFabricanteBody?
$('tr > td:last-child').remove();
or
$('tr > td').last().remove();
see demo HERE and HERE.

How to Insert an Inline Razor Expression into Javascript

I have the following script:
<script type="text/javascript">
function addRow() {
var count = $("#tblUploadDocs").prop('rows').length;
count += 1;
alert(count);
var html = '<tr>';
html += '<td><input type="file" name="files" id="file' + count + '" /></td>';
html += '<td>Bu dilden</td>';
html += '<tr>';
alert(html);
}
</script>
I am trying to insert the following line into the script, but could not achieve the desired result:
<td>#Html.DropDownList("ddlFromLanguage1", ViewBag.Languages as SelectList)</td>
I tried both and #: but could not make it work. I am looking forward to hearing to a solution.
Thanks in advance
Use the <text> pseudo-element, as described here, to force the razor compiler back into content mode:
<script type="text/javascript">
function addRow() {
<text>
var count = $("#tblUploadDocs").prop('rows').length;
count += 1;
alert(count);
var html = '<tr>';
html += '<td><input type="file" name="files" id="file' + count + '" /></td>';
html += '<td>Bu dilden</td>';
html += '<tr>';
alert(html);
</text>
}
</script>

Categories

Resources