I have a fullcalendar calendar where the click-events having sweet-alert 2 popups in the functions. The pop up boxes have multiple drop downs that are built using sweet-alert HTML functionality. Here's an example of the code,
eventClick: function (calEvent, jsEvent, view, date) {
var clickValue = calEvent.description;
if (clickValue != 'OWEDVALUE') {
var btn = "button";
drop = drop.replace("select-style-purple", "select-style-green");
options = options.replace("select-style-purple", "select-style-green");
var title = calEvent.title.replace("\n", "<br />");
swal({
title: moment(calEvent.start).format("MM/DD/YYYY"),
type: 'info',
inputClass: 'select-style-green',
inputValue: calEvent.teachNum,
html: title + '<br />' +
'Notes: ' + calEvent.description + '<br /><br />Select A New Teacher: <br /><br />' + options + '<p></p>Select A New Service: <br /><br />' + drop +
'<br /><br /><div style="border:2px solid green;" >Update Hours: ' +
'<input type="text" autofocus id="newHours" style="display:block !important;" class="sweet-alert-input"/>' +
'<input type="hidden" id="oldHours" value="' + calEvent.hours + '" /></div>' +
'<button type="' + btn + '" id="btnA" value="' + calEvent.id + '" style="background-color: #D46752 !important;" class="sweet-alert2-button">Delete Record</button> ' +
'<button type="' + btn + '" id="btnB" value="' + calEvent.id + '" class="sweet-alert2-button">Update Record</button> ' +
'<button type="' + btn + '" id="btnC" style="background-color: #B9B9B9 !important;" class="sweet-alert2-button">Cancel</button>',
showConfirmButton: false
});
$(this).css('border-color', 'red');
}
This is an example of one of the drop down boxes built in a javascript var.
options = '<select id="teacherDrop" class="select-style-green">';
for (var i = 0; i < record_array.length; i++) {
options += '<option value="' + record_array[i].teachNum + '" ';
if (record_array[i].teachName == data[0].teacher)
options = options + ' selected="selected" >' + record_array[i].teachName + 'TEST</option>';
else
options = options + '>' + record_array[i].teachName + 'TEST</option>';
}options += '</select>';
What I would like to do is to rebuild the drop downs(updating the selected value) after every click-event ajax call, so I need to rebuild the actual eventClick functions not the eventSources. I have tried multiple things to no avail.
Here is the function that gets called when one of the submit buttons gets pressed from the Sweet-Alert.
$(document).on('click', "#btnB", function () {
if ($.isNumeric($("#newHours").val())) {
var qString;
qString = "id=" + this.value;
qString += "&teacherId=" + $("#teacherDrop").val();
qString += "&hours=" + $("#newHours").val();
qString += "&service=" + $("#serviceDrop").val();
$.ajax({
type: "POST",
url: "_data_ManageHomebound_Students.aspx?qt=updateStudentRecord",
data: qString,
async: false,
success: function (data) {
data = JSON.parse(data);
swal.close();
$('#calendar').fullCalendar('removeEvents', data[0].id);
$("#calendar").fullCalendar('renderEvent', {
title: "Service Type: " + data[0].serviceType + "\nTeacher: " + data[0].teacher + "\nHours: " + $("#newHours").val(),
id: data[0].id,
start: data[0].start,
end: data[0].start,
allDay: data[0].allDay,
description: data[0].description,
teacher: data[0].teacher,
homeBoundPaidID: data[0].homeBoundPaidID,
teachNum: data[0].teachNum,
serviceType: data[0].serviceType,
color: 'green',
textColor: 'black'
}, false);
$('#ant').addClass('animated zoomInDown').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function () {
$(this).removeClass('animated zoomInDown');
});
//Here I'm going to rebuild the service type drop down and try to recreate all click events.
var options;
options = '<select id="teacherDrop" class="select-style-green">';
for (var i = 0; i < record_array.length; i++) {
options += '<option value="' + record_array[i].teachNum + '" ';
if (record_array[i].teachName == data[0].teacher)
options = options + ' selected="selected" >' + record_array[i].teachName + 'REBUILT</option>';
else
options = options + '>' + record_array[i].teachName + 'REBUILT</option>';
}
options += '</select>';
var temp = $("#hoursGiven").val();
if ($("#newHours").val() >= $("#oldHours").val()) {
temp = parseFloat(temp) + (parseFloat($("#newHours").val()) - parseFloat($("#oldHours").val()));
} else {
temp = parseFloat(temp) - (parseFloat($("#oldHours").val()) - parseFloat($("#newHours").val()));
}
$("#hoursGiven").val("");
$("#hoursGiven").val(temp);
$("#hoursOwed").val(parseFloat($("#totHoursNeeded").val()) - parseFloat(temp))
}
});
} else {
sweetAlert({
title: "Oops!",
text: "Please Make Sure Pay Rate is Numeric. \nPlease fix form and try again.",
type: "error"
});
return false;
}
});
So after the Ajax is successful I rebuild the options var that holds the drop down information for Sweet-Alert. This is the point where I need all of the click-events to be rebuilt to use the updated code(options var). The purpose of this is I'm trying to get the drop downs to have a pre-selected value of the most recently used item(teacher, etc...).
Related
I'm learning JS while doing a POS System, and I'm having a hard time trying to figure out how to check if the product added is already scanned before inserting and if so, change the quantity input instead.
So far when I scan the product id it inserts without a problem, but when I scan the same id it inserts in a new row. It seem that my function comprobacion isn't working. I tried with other using a for to search in the rows, and I tried some solutions that I found online but nothing seems to work.
here is an example of what its happening
https://gfycat.com/respectfultemptingeastrussiancoursinghounds
idProductos is the primary key and is hidden in the rows, so im introducing codigo (it's another unique column, both cannot be null).
Can someone help me? I'm lost.
This is my code
$.ajax({
method: "POST",
url: "../php/venta.php",
data: param,
success: function(data) {
if (data != null) {
var idProductos,
Codigo,
nombre,
precioVenta;
// console.log(data);
var rows = jQuery.parseJSON(data);
idProductos = rows[0].idProductos;
Codigo = rows[0].Codigo;
nombre = rows[0].nombre;
precioVenta = rows[0].precioVenta;
(idProductos)
if (comprobacion(idProductos) == false) {
var nuevoValor = $(parseInt($('.inputCantidad')[i]).val()) + 1;
$($('.inputCantidad')[i]).val(nuevoValor);
var valorImporte = $($('.inputprecioVenta')[i]).val() * nuevoValor;
$($('.inputImporte')[i]).val(valorImporte);
} else {
var table = document.getElementById('tablaVenta');
var newRow = document.createElement("tr");
newRow.align = "center";
var contentRow =
'<td><input type="hidden" class="inputId" value="' + idProductos + '">' + Codigo + '</td>' +
'<td>' + nombre + '</td>' +
'<td><input class="inputprecioVenta" value="' + precioVenta + '"></td>' +
'<td><input class="inputCantidad" value="1"></td>' +
'<td><input class="inputImporte" value="' + precioVenta + '"></td>';
newRow.innerHTML = contentRow;
table.appendChild(newRow);
}
}
},
error: function(jqXHR, textStatus, errorThrown) { //errores
alert(jqXHR + textStatus + errorThrown);
},
})
}
the function comprobacion
function comprobacion(idProductos) {
var id = $(idProductos).val();
$('tbody tr').each(function() {
if ($(this).val() == id) {
return false;
}
});
return true;
}
I would add the id to the row using a custom data attribute, like data-id, and use that, along with some clever selector creation to quickly identify if the id has been used before.
$.ajax({
method: "POST",
url: "../php/venta.php",
data: param,
success: function(data) {
if (data != null) {
var idProductos,
Codigo,
nombre,
precioVenta;
// console.log(data);
var rows = jQuery.parseJSON(data);
idProductos = rows[0].idProductos;
Codigo = rows[0].Codigo;
nombre = rows[0].nombre;
precioVenta = rows[0].precioVenta;
(idProductos)
if (comprobacion(idProductos) == false) {
var nuevoValor = $(parseInt($('.inputCantidad')[i]).val()) + 1;
$($('.inputCantidad')[i]).val(nuevoValor);
var valorImporte = $($('.inputprecioVenta')[i]).val() * nuevoValor;
$($('.inputImporte')[i]).val(valorImporte);
} else {
var table = document.getElementById('tablaVenta');
var newRow = document.createElement("tr");
newRow.align = "center";
/* Add the line below */
newRow.setAttribute("data-id", idProductos);
var contentRow =
'<td><input type="hidden" class="inputId" value="' + idProductos + '">' + Codigo + '</td>' +
'<td>' + nombre + '</td>' +
'<td><input class="inputprecioVenta" value="' + precioVenta + '"></td>' +
'<td><input class="inputCantidad" value="1"></td>' +
'<td><input class="inputImporte" value="' + precioVenta + '"></td>';
newRow.innerHTML = contentRow;
table.appendChild(newRow);
}
}
},
error: function(jqXHR, textStatus, errorThrown) { //errores
alert(jqXHR + textStatus + errorThrown);
},
})
Then, the comprobacion function becomes easier:
function comprobacion(idProductos) {
return $('tbody tr[data-id="' + idProductos + '"]').length === 0;
}
Set id to HTML inputs, is more quick to find ProductID with JS.
'<td><input type="hidden" id="hid_' + idProductos + '" class="inputId" value="' + idProductos + '">' + Codigo + '</td>' +
'<td>' + nombre + '</td>' +
'<td><input id="hid_' + idProductos + '" class="inputprecioVenta" value="' + precioVenta + '"></td>' +
'<td><input id="qty_' + idProductos + '" class="inputCantidad" value="1"></td>' +
'<td><input id="cst_' + idProductos + '" class="inputImporte" value="' + precioVenta + '"></td>';
Try $('tbody tr td').each(function().
The value is in the td, not the tr
I have two loops:
table loop: fills the table rows
dropdown loop: fills the dropdowns with typeid.data[i].TypeId, add a select in the last dropdown
My dropdown does not fill according to its record and I don't understand why.
var QuestionId = data[i].QuestionOid;
var fkid = data[i].FkSource;
var selectdata = data[i];
var selectinnerhtml = "<span><select id = \"answer" + QuestionId + "\" name = \"answer" + QuestionId + "\" class=\"answer" + QuestionId + " form-control input-small\" > </select></span>";
$.ajax({
type: "GET",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: '/MYaPI/EmployeeDetails/' + data[i].TypeId,
success: function(datasa) {
var optionhtmls = '<option value="' +
0 + '">' + "--Select--" + '</option>';
$(".answer" + QuestionId).append(optionhtmls);
$.each(datasa, function(j) {
var optionhtmls = '<option value="' +
datasa[j].Oid + '">' + datasa[j].Title + '</option>';
$(".answer" + QuestionId).append(optionhtmls);
});
}
});
var newRows2select = "<tr class='rows'><a href = '' >" +
" <td QuestionCategoryTitle = " + selectdata.QuestionCategoryTitle + " QuestionHeader = " + selectdata.QuestionHeader + " ContentTypeId=" + selectdata.FkSource + " QuestionTypeId=" + selectdata.FkQuestionType + " QuestionOID=" + selectdata.QuestionOid + " CategoryOID=" + selectdata.FkQuestionCategory + " class=\"question-block\"><small style=\"color:slateblue;font-weight: bolder;display:none\">CATEGORY: " + selectdata.QuestionCategoryTitle + ",</small>" +
" <i class=\"deleteRow fas fa-trash float-right\"></i> " +
"<p> " + selectdata.QuestionHeader + "</p>" + selectinnerhtml + " </td></a> \"</tr>";
$("#table23").append(newRows2select);
I don't know the jQuery way, however it is easily achievable with plain JavaScript
var select = document.createElement("select");
var selectinnerhtml = document.createElement("span");
selectinnerhtml.appendChild(select);
$.each(datasa, function(j) {
//create a new option element
var option = document.createElement("option");
//set the value attribute
option.setAttribute("value", datasa[j].oid);
//fill the HTML tag
option.value = datasa[j].Title
//add the option to the select dropdown
select.add(option);
});
I am facing issues while adding the options in the select that I am generating dynamically using jQuery. I am fetching options from the database and I want to show all those options for each dynamically generated select tag.
Please tell me what i am doing wrong in my code?
Here is my function to add new row :
function addnewrow() {
var n = ($('.detail tr').length - 0) + 1;
var tr = '<tr>' +
'<td class="no">' + n + '</td>' +
'<td><input type="checkbox" class="till_check" name="till_check[' + till_check_counter + ']" id="prdct_till_check[' + till_check_counter + ']"></td>' +
'<td><select class="form-control barcode dyselect['+product_barcode_counter+']" name="barcode[' + product_barcode_counter + ']" id="prdct_barcode[' + product_barcode_counter + ']">'+'<option>Please select a bar code</option>'+'</select></td>' +
'<td><input type="text" class="form-control productname" id="brcode_product" name="productname[' + product_name_counter + ']" id="prdct_name[' + product_name_counter + ']"></td>' +
'<td><input type="text" class="form-control sm" name="sm[' + sm_counter + ']" id="prdct_sm[' + sm_counter + ']"></td>' +
'<td><input type="text" class="form-control spl" name="spl[' + spl_counter + ']" id="prdct_spl[' + spl_counter + ']"></td>' +
'<td><input type="text" class="form-control quantity" name="quantity[' + product_quantity_counter + ']" id="prdct_qty[' + product_quantity_counter + ']"></td>' +
'<td><input type="text" class="form-control price" name="price[' + product_price_counter + ']" id="prdct_price[' + product_price_counter + ']"></td>' +
'<td><input type="text" class="form-control discount" name="discount[' + product_discount_counter + ']" id="prdct_discount[' + product_discount_counter + ']"></td>' +
'<td><input type="text" class="form-control amount" name="amount[' + product_amount_counter + ']" id="prdct_amount[' + product_amount_counter + ']"></td>' +
'<td><a href="#" class="remove">Delete</td>' +
'</tr>';
$('.detail').append(tr);
//increamenting the counter
++till_check_counter;
++product_name_counter;
++product_quantity_counter;
++sm_counter;
++spl_counter;
++product_price_counter;
++product_discount_counter;
++product_amount_counter;
//setting the validation rules for every product attribute by calling the function
createValidation();
get_barcodes();
}
Here is the function for getting barcodes from database :
function get_barcodes() {
$.ajax({
url: 'http://localhost/retail/main/ajax_barcodes/',
type: 'POST',
datatype: 'json',
data: {
'barcode': $('#brcode option:selected').val()
},
success: function(data) {
/*var obj = JSON.parse(data);
console.log(obj.brcode.name);*/
var myselect = $('.dyselect[' + product_barcode_counter + ']');
var barcodes = JSON.parse(data);
for (var i = 0; i < barcodes.brcode.length; i++) {
//console.log(barcodes.brcode[i].name);
//console.log(barcodes.brcode[i].barcode);
var options = ('<option value="' + barcodes.brcode[i].barcode + '">' + barcodes.brcode[i].barcode + '</option>');
console.log(options);
// $('.dyselect['+product_barcode_counter+']').append("Hello world");
$('.dyselect').text('dfsgfisdgfsiudfgsdf');
}
}
});
}
Please do not consider the commented code.
You are not appending your options to the DOM anywhere.
myselect.append(options); // Missing this line
You are incrementing your ++product_barcode_counter after adding a row
//increamenting the counter
++till_check_counter;
++product_name_counter;
++product_quantity_counter;
++sm_counter;
++spl_counter;
++product_price_counter;
++product_discount_counter;
++product_amount_counter;
so, by the time you are accessing the product_barcode_counter inside the ajax success its incremented.
Here,
your var myselect = $('.dyselect_' + product_barcode_counter); selection is wrong it is returning nothing.
You have to bind your id to the ajax so that you can read the value on ajax success.
$.ajax({
url: 'http://localhost/retail/main/ajax_barcodes/',
type: 'POST',
datatype: 'json',
data: {
'barcode': $('#brcode option:selected').val()
},
success: function(id,data) {
//Here id is what you need to use to select the correct select.
}.bind(this,product_name_counter-1)
);
JS
function get_barcodes() {
$.ajax({
url: 'http://localhost/retail/main/ajax_barcodes/',
type: 'POST',
datatype: 'json',
data: {
'barcode': $('#brcode option:selected').val()
},
success: function(id,data) {
var myselect = $('.dyselect_' + id);
var barcodes = JSON.parse(data);
for (var i = 0; i < barcodes.brcode.length; i++) {
var options = ('<option value="' + barcodes.brcode[i].barcode + '">' + barcodes.brcode[i].barcode + '</option>');
myselect.append(options); // Missing this line
}
}.bind(this,product_name_counter-1)
});
}
OR you can use closure
success: (function(id){
return function(data) {
//Here id is what you need to use to select the correct select.
}
})(product_name_counter-1);
JS
function get_barcodes() {
$.ajax({
url: 'http://localhost/retail/main/ajax_barcodes/',
type: 'POST',
datatype: 'json',
data: {
'barcode': $('#brcode option:selected').val()
},
success: (function(id){
return function(data) {
var myselect = $('.dyselect_' + id);
var barcodes = JSON.parse(data);
for (var i = 0; i < barcodes.brcode.length; i++) {
var options = ('<option value="' + barcodes.brcode[i].barcode + '">' + barcodes.brcode[i].barcode + '</option>');
myselect.append(options); // Missing this line
}
}
}
})(product_name_counter-1);
});
}
Does anybody have any idea why this is not allowing the form to submit? I'm attempting to use Rotten Tomatoes API with a user search function.
FORM IN PHP PAGE
<form name="myform" action="" method="GET"><h3>Search for a movie here:</h3><br>
<input type="text" id="inputbox" value="">
<input type="submit" name="submit" value="Go!">
JAVASCRIPT
$('form[name="myform"]').submit(function() {
$('#films table').empty(); //removes previous search results before adding the new ones.
var apikey = "frceg2d5djxezaedgm3qq94h";
var baseUrl = "http://api.rottentomatoes.com/api/public/v1.0";
var moviesSearchUrl = baseUrl + '/movies.json?apikey=' + apikey;
var query = form.inputbox.value; //uses the value from the input box as the query search
// sends the query
$.ajax({
url: moviesSearchUrl + '&q=' + encodeURI(query),
dataType: "jsonp",
success: searchCallback // if successful, run searchCallback function
});
// receives the results
function searchCallback(data) {
$('#films table').append('Found ' + data.total + ' results for ' + query);
var movies = data.movies;
$.each(movies, function(index, movie) {
$('#films table').append('<tr><td width="70" rowspan="2"><a href="' + movie.links.alternate +
'" title="Click here to view film information for ' + movie.title + '."><img class="ajaximage" src="'
+ movie.posters.thumbnail + '" /></a></td><td class="ajaxfilmlisttitle"><h3><a href="' + movie.links.alternate +
'" title="Click here to view film information for ' + movie.title + '.">' + movie.title + '</a></h3>Release year: '
+ movie.year + '</td></tr><tr><td class="ajaxfilmlistinfo">Audience Score: ' + movie.ratings.audience_score +
'%<br>' + 'Cinema Release Date: ' + movie.release_dates.theater +
'<br>Runtime: ' + movie.runtime + ' minutes</td></tr>');
});
};
});
I tested with this code and it works:
<form name="myform" action="" method="GET">
<h3>Search for a movie here:</h3>
<input type="text" id="inputbox" value="" />
<input type="submit" name="submit" value="Go!" />
</form>
<script>
$(function(){
$('form[name="myform"]').on('submit', function(e) {
e.preventDefault();
$('#films table').empty(); //removes previous search results before adding the new ones.
var apikey = "frceg2d5djxezaedgm3qq94h";
var baseUrl = "http://api.rottentomatoes.com/api/public/v1.0";
var moviesSearchUrl = baseUrl + '/movies.json?apikey=' + apikey;
var query = $('#inputbox').val(); //uses the value from the input box as the query search
// sends the query
$.ajax({
url: moviesSearchUrl + '&q=' + encodeURI(query),
dataType: "jsonp",
success: searchCallback // if successful, run searchCallback function
});
// receives the results
function searchCallback(data) {
$('#films table').append('Found ' + data.total + ' results for ' + query);
var movies = data.movies;
$.each(movies, function(index, movie) {
$('#films table').append('<tr><td width="70" rowspan="2"><a href="' + movie.links.alternate +
'" title="Click here to view film information for ' + movie.title + '."><img class="ajaximage" src="'
+ movie.posters.thumbnail + '" /></a></td><td class="ajaxfilmlisttitle"><h3><a href="' + movie.links.alternate +
'" title="Click here to view film information for ' + movie.title + '.">' + movie.title + '</a></h3>Release year: '
+ movie.year + '</td></tr><tr><td class="ajaxfilmlistinfo">Audience Score: ' + movie.ratings.audience_score +
'%<br>' + 'Cinema Release Date: ' + movie.release_dates.theater +
'<br>Runtime: ' + movie.runtime + ' minutes</td></tr>');
});
};
});
});
</script>
There were a couple of problems:
The form.inputbox.value did not work, change it to $('#inputbox').val()
Add e.preventDefault() to prevent the from from being submitted
There was a missing });
Change $('form[name="myform"]').submit(function() { to $('form[name="myform"]').on('submit', function(e) {
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