passing value to a dynamic created function in javascript - javascript

I am having some problems while creating a dynamic webpage in javascript.
My idea is to read a list of events and people signed up on them. I create a page with all events (each event is a button) and clicking on one of them, see the list of users.
This works fine. But now, I am adding a button to export some of these users to an excel file. And I want to add a button with an onClick function like this:
...onclick=functionÇ(id_Event, numberOfUsers, listOfUsers)...
Inside of the html code generated by javascript. I found some problems also doing like this so I changed so:
var td = document.createElement("td");
var input = document.createElement("input");
input.setAttribute("type","button");
input.setAttribute("value","Exportar a Excel CSV");
input.onclick = function() {
saveExcelFunctionControl(arrayNumberUsersInEvents[i], response);
};
td.appendChild(input);
document.getElementById("added"+element[i].id_Event).appendChild(td);
I created a global array called arrayNumberUSersInEvents in which I am adding in each possition, people subscribed. i, is the id counter for each position.
But even this, I am getting an undefined while reading the value of the firsdt parameter. I think it is a problem of dynamic data, I am not executing the function I want to each time I click the button. Do you know how to do something like this?
To sum up: My problem is that I want to pass some arguments to a function in a dynamic created page. I don't know how to pass the data and read the correct parameters inside.
I added my code because one user asked for it:
for(i = 0; i < element.length; i++){
$(".eventsControl").append(
'<li id="listControl'+ element[i].id_Event +'">'+
'<a href="#EventControl' + element[i].id_Event + '"' + 'data-transition="slidedown">'+
'<img class="crop" src= "' + element[i].image + '" />'+
'<h2>' + element[i].name + '</h2>'+
'<p>' + "Desc: " + element[i].description +'</p>'+
'</a>'+
'</li>'
).listview('refresh');
//console.log(response);
//BUCLE for setting all users in each event. Better use some string and after, join all of them
header = ' <div width="100%" data-theme = "e" data-role="page" id='+ element[i].id_Event +
' data-url="EventControl' + element[i].id_Event + '"> ' +
' <div data-theme = "a" data-role="header"><h1>Lista de Asistencia</h1> ' +
' </div>'+
' <div data-role="content"> ' +
' <fieldset data-role="controlgroup" data-type="horizontal" style="text-align: center">' +
' <div style="width: 500px; margin: 0 auto;">';
//header = header + '<input data-theme = "c" onclick="saveExcelFunctionControl(this)" id="saveExcelControl' + element[i].id_Event + '" type="button" value = "Guardar a excel"></br>';
eval('var numberUsers' +element[i].id_Event + "=1");
arrayNumberUsersInEvents[i] = 0;
if(response.length>0){
bucle = ' <table width="100%" border="1" align="left"><tr>'+
' <th>Nombre</th>'+
' <th>Primer apellido</th>'+
' <th>Segundo apellido</th>'+
' <th>NIF</th>'+
' <th>Asistencia</th>'+
' </tr>';
for(iData = 0; iData < response.length; iData++){
if(element[i].id_Event == response[iData].id_Event){
//console.log(response[iData].name);
bucle = bucle + '<tr><td>'+ eval('numberUsers' +element[i].id_Event) +'</td><td>'+ response[iData].name +'</td><td>'+
response[iData].surname1 +'</td><td>'+
response[iData].surname2 +'</td><td>'+
response[iData].NIF + '</td>'+
'<td> '+
'<input type="checkbox" id="checkBox'+element[i].id_Event+'_'+iData+'" name="option'+iData+'" value="'+iData+'"> '+
'</td>'+
'</tr>';
eval('numberUsers' +element[i].id_Event + "++");
arrayNumberUsersInEvents[i] = arrayNumberUsersInEvents[i]+1;
}
}
//header = header + '<input data-theme = "a" onclick="saveExcelFunctionControl(\""element[i].id_Event "\","" + numberUsers + "\",\"" + response+ "\"")" id="saveExcelControl' + element[i].id_Event + '" type="button" value = "Guardar a excel"></br>';
//header = header + '<input data-theme = "a" onclick="saveExcelFunctionControl(""+numberUsers+"")" id="saveExcelControl' + element[i].id_Event + '" type="button" value = "Guardar a excel"></br>';
bucle = bucle + '</table>';
$("#controlList").after(header + bucle + '<div id=added'+element[i].id_Event+'></div>');
var td = document.createElement("td");
var input = document.createElement("input");
input.setAttribute("type","button");
input.setAttribute("value","Exportar a Excel CSV");
input.onclick = function() {
saveExcelFunctionControl(arrayNumberUsersInEvents[i], response);
};
td.appendChild(input);
document.getElementById("added"+element[i].id_Event).appendChild(td);
}
}
},
error: function(xhr, status, message) { alert("Status: " + status + "\nControlGetEventsRegister: " + message); }
});

You can use closure to pass parameters to dynamically created onclick handler:
input.onclick = (function() {
var arr = arrayNumberUsersInEvents[i];
var resp = response;
return function() {
saveExcelFunctionControl(arr, resp);
}
})();
How do JavaScript closures work?

var td = document.createElement("td");
var input = "<input type='button' value='Exportar a Excel CSV'";
input+= "onclick='saveExcelFunctionControl(""" +arrayNumberUsersInEvents[i]+""","""+ response+""");' />";
};
td.textContent=input;
document.getElementById("added"+element[i].id_Event).appendChild(td);
try this way

Related

click a div in an .append with a loop

I am using an .append to populate a div-id and all that works fine, i even get the loop inside, however i would like to make an item clickable inside the loop and load a div that holds details of that item. This is what i got so far.
<div id="GameContainer"></div>
var gamesData; //A global variable to hold Ajax response.
$.ajax({
type: 'Get',
url: "http://"URL/" + GamesList,
success: function (data) {
gamesData = data; // add the Ajax data to the global variable
var dynamic = "";
for (i = 0; i < data.length; i++) {
dynamic += '<div id="' + data[i].id_game + '" class="TopContainerCel" onclick="GameDetails(' + data[i] + ')">'
+ ' <div class="TopContainerCelBackground">'
+ ' <img class="TopContainerCelImage" src="' + data[i].CoverImage + '" />'
+ ' </div>'
+ ' <div class="TopContainerCelName">' + data[i].Name + '</div>'
+ ' </div>'
};
$('#GameContainer').append(''
+ '<div class="TopContainerScroll">'
+ dynamic
+ '</div>');
}
})
// based on the solution of K K [extended with an array.find]
added the global variable gamesData and filled it with the Ajax reponse
$(document).on("click", ".TopContainerCel", function () {
var elem = $(this);
console.log(elem[0].id) // the actual id clicked is there
console.log(gamesData) // all the data of the Ajax response is there
GameID = elem[0].id;
var gameData = gamesData[elem.data("id")]; // part that does not work
var gameData = gamesData.find(x => x.id_game == GameID); // works!
//gameData has the data
console.log(gameData)
});
So i found a diffent way of combining the two data together by using a find in the array. Is there a better way of doing this? If so why and what is the difference?
Try something similar to this:
var gamesData;//A global variable to hold Ajax response.
$.ajax({
type: 'Get',
url: "http://URL/" + GamesList,
success: function (data) {
gamesData = data;
var dynamic = "";
for (i = 0; i < data.length; i++) {
dynamic += '<div id="' + data[i].id_game + '" data-id="'+data[id]+'" class="TopContainerCel">'
+ ' <div class="TopContainerCelBackground">'
+ ' <img class="TopContainerCelImage" src="' + data[i].CoverImage + '" />'
+ ' </div>'
+ ' <div class="TopContainerCelName">' + data[i].Name + '</div>'
+ ' </div>'
};
$('#GameContainer').append(''
+ '<div class="TopContainerScroll">'
+ dynamic
+ '</div>');
}
})
$(document).on("click",".TopContainerCel",function(){
var elem = $(this);
var gameData = gamesData[elem.data("id")];
//gameData has your data
});
Note: The approach here is to store ajax response in a variable. From your code, the response is an array. So, when you iterate over the items, get the index of the clicked item in any way you prefer and access the detail of game using the index from gamesData.
you can add data-id to dynamic like : <div data-id="'+data[i].id+'".
then you can do :
var games = {};
for (i = 0; i < data.length; i++) {
games[data[i].id_game] = data[i];
dynamic += '<div id="' + data[i].id_game + '" class="TopContainerCel" onclick="GameDetails(' + data[i] + ')">'
+ ' <div class="TopContainerCelBackground">'
+ ' <img class="TopContainerCelImage" src="' + data[i].CoverImage + '" />'
+ ' </div>'
+ ' <div class="TopContainerCelName">' + data[i].Name + '</div>'
+ ' </div>'
};
$("#GameContainer").on('click','.TopContainerCel',function() {
var $this = $(this);
console.log(games[$this.data('id')])
// code logic here
});

Best Way to make one section of a LI editable

What is the best way to make JUST card.price editable? I've futzed around with several different ways that seemed stupid simple, but it just isn't producing the right results. Does anyone out there have some suggestions?
html += "<li class='list-item ui-state-default' id=" + i + ">" +
card.card_name + ' - ' + card.price +
"<button class='removeThis'>" +
"X" + "</button>" + "</li>";
Here's a simple way to do that with input elements. Simplified example to illustrate it:
var card = {};
card.card_name = "Card Name";
card.price = "4.00";
var inputBeg = "<input size=8 style='border: none;' value='$";
var inputEnd = "'>";
var html = "";
for (var i = 0; i < 3; i++) {
html += "<li class='list-item ui-state-default' id=" + i + ">" +
card.card_name + ' - ' + inputBeg + card.price + inputEnd + "<button class='removeThis'>" +
"X" + "</button>" + "</li>";
}
document.body.innerHTML = html;
You could get much fancier with the styling if you wanted to.

how to use image tag

Can someone help me out in inserting an image in the below function. I've used a json object that returns values for campaignid and campaignname.
<script>function searchedCampaigns(data) {
if (data[0].length > 0) {
var searchcmp = "";
for (var j = 0; j < data[0].length; j++) {
var input = document.createElement("input");
console.log(input.name);
searchcmp += '<input type="checkbox" id=' + data[0][j].campaignId + ' name=' + data[0][j].campaignName + '/>' +
**// image to be inserted here**
+ data[0][j].campaignName + '<br/>'; // value
}
$("#newcamp").html(searchcmp);
}}</script>
output should be this
I'm getting the checkbox as well as the campaign name. I want the image in between these two.
As simple as this..
searchcmp += '<input type="checkbox" id=' + data[0][j].campaignId + ' name=' + data[0][j].campaignName + '/>' +
'<img src="'+yourimageurlfromdata+'"/>'+
'data[0][j].campaignName + '<br/>';
I suggest you a code like this one:
<input type="checkbox"><img src="Image.PNG">Test</img></input>
Also, based on your code, it can be updated like this:
searchcmp += '<input type="checkbox" id=' + data[0][j].campaignId + ' name=' + data[0][j].campaignName + '><img src=' + YOUR_URL_LOCATION + ' />' + data[0][j].campaignName + '</input><br/>';
Where YOUR_URL_LOCATION, can be in the JSON or somewhere else.
It's going to display something like this:

Javascript html gallery

Im editing/creating the following script for my website.
As you can see below I want him to add a <div class="row"> at the start of every row. (Hard to explain).
Then with the var "getal" I want him to END this DIV tag after 4 items in it (4x the foreach loop)
But the way I'm trying to do it with the If loops is not working. Any ideas? (The code is working fine without the <div class="row">, if loops and var getal.
function show_albums (response) {
var getal = 0;
//hide main loader
$('#loading_gallery').hide();
$.each(response.data, function(key, value) {
//create html structure
//rijen teller
if (getal = 0 ) {
var html = '<div class="row">';
$('#albums').append(html);
}
//albums
var html = '' +
'<div class="col-lg-3 col-md-3 col-xs-3 thumb" id="album_' + key + '"> ' +
'<img class="img-thumbnail" id="album_cover_' + key + '" />' +
'<img id="loading_' + key + '" src="images/ajax-loader.gif" />' +
'<h2>' + value.name + '</h2>' +
'<p>' + value.count + ' foto's</p>' +
'</div>';
getal++;
if (getal = 4) {
var html = '</div>';
$('#albums').append(html);
getal = 0;
}
$('#albums').append(html);
}
}
You are using the assignment operator = instead of the comparison operator == in your if statements. Try replacing those.

JS/Ajax Image upload- producing multiple image preview thumbnail of the same content

I am currently working with an Image uploader(Source Files). I am having difficulties creating duplicate preview fields. I am creating the preview image form but it is only displaying one thumbnail. How can i get the Js to give me two thumbnails? Here is a LIVE EXAMPLE and further explanation to my source code
This what I initially want to do:
Snippet of JS for creating the preview Image forms(thumbnails)
upLoaderPreviewer.js
<script>
function createImageForm(index) {
var form = '';
form += '<div><table cellspacing="0">';
form += '<tr><td class="label">'
+ '<label for="imageToUpload' + index + '">'
+ $.uploaderPreviewer.messages.imageLabel + ' ' + index + ':</label></td>';
form += '<td class="removeImageButton">'
+ '</td>';
form += '<td class="imageFormFileField">'
// BUG: If the "enctype" attribute is assigned with jQuery, IE crashes
+ '<form enctype="multipart/form-data">'
+ '<input id="imageToUpload' + index + '" type="file" />'
+ '<input type="hidden" name="currentUploadedFilename"'
+ ' class="currentUploadedFilename" /></form>'
+ '</td></tr>';
form += '<tr><td></td><td></td><td>'
+ '<div class="previewImage" style="float:left; margin:10px 10px 10px 0; "><img /></div>'
+ '<button type="button" class="small removeImage"></td></td></tr></table></div>';
return form;
};
</script>
try this:
replace the function 'displayImage' on the uploaderpreviewer.js with this:
function displayImage($previewDiv, imageUrl) {
//New
var yourCustomPreview = $('#custompreview');
var imageFilename = imageUrl.substr(imageUrl.lastIndexOf('/') + 1);
$previewDiv
.removeClass('loading')
.addClass('imageLoaded')
.find('img')
.attr('src', imageUrl)
.show();
$previewDiv
.parents('table:first')
.find('input:hidden.currentUploadedFilename')
.val(imageFilename)
.addClass('imageLoaded');
$previewDiv
.parents('table:first')
.find('button.removeImage')
.show();
//New
yourCustomPreview.prepend('<img src="' + imageUrl + '"/>');
}
and add this where you whant to duplicate the thumb:
<div id="custompreview">
</div>

Categories