How to set Onclick dynamic to generated rows? - javascript

function GetPage(pageIndex) {
debugger;
$.ajax({
cache: false,
//url: "/EmailScheduler/",
url: '#(Url.RouteUrl("EmailScheduler"))',
type: "POST",
data: { "selectValue": pageIndex },
traditional: true,
dataType: "json",
success: function (data) {
debugger;
$('#GridRows').empty();
$('#pager').empty();
var trHTML = '';
var htmlPager = '';
$.each(data.Customers, function (i, item) {
trHTML += '<table class="table-bordered col-offset-12"><tr style="text-align:center">'
+'<td id="tblFirstName"> ' + item.FirstName + '</td>'
+'<td id="tblLastName"> ' + item.LastName + '</td>'
+'<td id="tblEmailID"> ' + item.EmailID + '</td>'
+'<td id="tblCustomerType"> ' + item.CustomerType + '</td>'
+'<td id="tblCustomerDesignation"> ' + item.CustomerDesignation + '</td>'
+' <td><div class="checkbox control-group"><label><input type="checkbox" id="item.CustomerID" value="item.CustomerID" onclick="AddRemoveCustomer(item.CustomerID)" class="checkBoxClass"/></label></div></td></tr></table>'
});
$('#GridRows').append(trHTML);
if (data.Pager.EndPage > 1) {
htmlPager += '<ul class="pagination">'
if (data.Pager.CurrentPage > 1) {
htmlPager += '<li><input class="myButton" style="width:25px;height:25px;" type="button" id="1" style="font-weight:bold;" value="<<" /></li><li><input type="button" class="myButton" id="' + (data.Pager.CurrentPage - 1) + '"value="<"></li>'
}
for (var page = data.Pager.StartPage; page <= data.Pager.EndPage; page++) {
htmlPager += '<li class="' + (page == data.Pager.CurrentPage ? "active" : "") + '"><input type="button" class="myButton" id="' + page + '" value="' + page + '"/></li>'
}
if (data.Pager.CurrentPage < data.Pager.TotalPages) {
htmlPager += '<li><input type="button" class="myButton" id="' + (data.Pager.CurrentPage + 1) + '" value=">"/></li><li><input type="button" class="myButton" id="' + (data.Pager.TotalPages) + '" value=">>"/></li>'
}
htmlPager += '</ul>'
}
$('#pager').append(htmlPager);
},
error: function (jqXHR, textStatus, errorThrown) {
debugger;
}
});
}
**
Scenario:-
**
In this ajax table rows generated.
How to call onClick function for checkbox in Ajax generated rows?
I want to call onClick function in which checked id's stored in hidden
field.
what should i do?

try to update :
+' <td><div class="checkbox control-group"><label><input
type="checkbox" id="'+item.CustomerID+'"
value="'+item.CustomerID+'" class="checkBoxClass"/>
</label></div></td></tr></table>'
and add this :
$(document).on('click', '#GridRows .checkBoxClass' ,
function(){
alert('hello');//todo something....
});

Try to do something like this
function delegateAction(){
$('.checkBoxClass').click(function(event){
// do some action
});
}
delegateAction();
After ajax load you can call "delegateAction()", and the event click will be activated.

Related

How to call a thymeleaf modal fragment from a javascript generated link?

I have a javascript function that renders a table from an ajax call.
The row rendering bit is:
function buildTable(id) {
trHTML = null;
$.ajax({
type: "GET",
url: siteroot + "apiURL" + id,
data: {},
dataType: "json",
cache: false,
success: function (data) {
for (i = 0; i < data.length; i++) {
trHTML +=
'<tr>' +
'<td>' + data[i].value +
'<a class="pull-right" href="#" data-toggle="modal" data-target="#edit-modal" > ' +
'<span class="pull-right glyphicon glyphicon-pencil"></span>' +
'</a>' +
'</td>' +
'<td>' + data[i].text + '</td>' +
'<td>' + data[i].description + '</td>' +
'</tr>';
}
$('#resourceTable').append('<tbody>' + trHTML + '</tbody>');
},
error: function (msg) {
alert(msg.responseText);
}
});
}
And the modal is defined as:
<div th:replace="../../modals/modal"></div>
The issue I am facing is that the link is here on the rendered table, but when I click it, the modal does not come on.
What am I not seeing here?

How to get Dropdownlist value inside HTML Table

I have a html table looks like below,and I want to get the dropdownlist value in table row by select the dropdownlist to a variable,when I select the second row dropdownlist it always pass the first row dropdownlist value,how to get the dropdownlist value by selected Row.
My Code is :
var table = $('<table id="tblprod" class="datagrid" border="0" class="table table-bordered"><thead ><tr><th><font size="2">Item ID<font></th><th><font size="2">Material Request Number</th><th><font size="2">Product Name</font></th><th><font size="2">Budget Qty</font></th><th><font size="2"><font size="2">Unit Code</font></font></th><th><font size="2"><font size="2">Unit Price</font></font></th><th><font size="2"><font size="2">Request Quantity</font></font></th><th><font size="2"><font size="2">Available Stock</font></font></th><th><font size="2"><font size="2">AlReady Issued</font></font></th><th><font size="2"><font size="2">Excess/Over Issues</font></font></th><th><font size="2"><font size="2">Balance Quantity</font></font></th><th><font size="2"><font size="2">Current Issue Quantity</font></font></th></tr></thead><tbody id=""></tbody></table>').addClass('product-table');
$('#product-load-tbl').append(table);
var totprice = 0;
$("#select-product").change(function () {
debugger;
CallBudgetNo();
CallBudgetProdQty();
document.getElementById('select-product').disabled = true;
var mrqno = $("#select-product :selected").val();
$.ajax({
type: "POST",
url: "/StockTransfer/CallMRN_No?MRNNO=" + mrqno,
contentType: "application/; charset=utf-8",
dataType: "json",
async: false,
success: function (grnhdmethod) {
if (grnhdmethod.length > 0) {
var i = 0;
$.each(grnhdmethod, function (index, item) {
debugger;
var row = '<tr>';
row += '<td class="ProId" id="idPoNum">' + $(this).attr('ItemId') + '</td>';
row += '<td class="MRNNo" id="idMrnNum">' + $(this).attr('MaterialRequest_No') + '</td>';
row += '<td class="col-md-1 inpprod" dir="rtl">' +
'<select id="select-txtpro' + index + '" class="select-Id" style="width: 200px" >"<option>--select Product--</option>"</select></td>';
row += '<td class="BudgetQty">' + '<input type="text" class="bdgt-qty' + $(this).attr('ItemId') + ' form-control col-md-3 center-block input-sm" data-id="bdgt-qty-" disabled="true">' + '</td>';
row += '<td class="UnitCode">' + $(this).attr('UnitCode') + '</td>';
row += '<td class="UnitPrice">' + $(this).attr('UnitPrice') + '</td>';
row += '<td class="ordrQty">' + $(this).attr('Quantity') + '</td>';
row += '<td class="stockval">' + '<input type="text" class="input-stk' + $(this).attr('ItemId') + ' form-control col-md-3 center-block input-sm" data-id="input-stk-" disabled="true">' + '</td>';
row += '<td class="allreadyrecived">' + $(this).attr('finalval') + '</td>';
if (TempIssuedtoWorkQty > tempNoBudQty) {
row += '<td class="OverIssueQty">' + (TempIssuedtoWorkQty - tempNoBudQty) + '</td>';
}
else {
row += '<td class="OverIssueQty">0</td>';
}
row += '<td class="blncQty" id="bal" dir="rtl" align="right">' + ($(this).attr('Quantity') - $(this).attr('finalval')) + '</td>';
if ($(this).attr('Quantity') == $(this).attr('finalval')) {
row += '<td class="col-md-1 inpqty" dir="rtl">' + '<input type="text" class="input-qty form-control col-md-3 center-block input-sm" data-id="input-qty" disabled="true">' + '</td>';
alert("Request Order Already Completed..!!!");
location.reload();
return true;
}
else {
row += '<td class="col-md-1 inpqty" dir="rtl">' + '<input type="text" class="input-qty form-control col-md-3 center-block input-sm" id="input-qty-' + $(this).attr('ItemId') + '" value="0">' + '</td>';
}
row += '</tr>';
table.append(row);
$.each(item.Products, function (i,product) {
$('#select-txtpro'+index).append(
$("<option></option>")
.text(product.ProductName)
.val(product.ProductId)
.attr('ProductId', item.ProductId)
.attr('ProductName', item.ProductName)
);
})
CallBudgetProdQty();
});
}
}
});
});
Here is my Onchange function :
$('#product-load-tbl').on('change', '.select-Id', function () {
debugger;
var proid = $('.select-Id').val();
var locid = ToIDtemp;
if (proid == "0") {
alert("Please Select Product..!");
}
else {
$.ajax({
type: "POST",
url: "/StockTransfer/CallAvailablestck?PROID=" + proid + "&LOCID=" + ToIDtemp,
contentType: "application/; charset=utf-8",
dataType: "json",
async: false,
success: function (prodlist) {
if (prodlist.length > 0) {
debugger;
AvailableStck = prodlist[0].AvaiStock
$('.input-stk' + prodlist[0].ItemId).val(AvailableStck)
}
else {
alert('Product Not in Stock')
}
}
});
}
});

Error: Cannot read property 'each' of undefined

I have a JavaScript code that returns values of a PHP and assembles an HTML table. Is giving the error can not read property of each undefined. I've looked several times without success. They could give me a hand?
The following code:
JavaScript:
function getListaItems(idprojeto) {
//alert(idprojeto);
jQuery.ajax({
type: "POST",
url: "get-lista-items.php?idprojeto=" + idprojeto,
//data: dataEvento,
dataType: 'json',
success: function(resposta) {
var str_html = '';
$.each(resposta, function(){
str_html = str_html + '<tr class="gradeA" id="' + this.id + '">' +
'<td class="center"><input type="checkbox" id="item[]" name="item[]" onchange="changeColor(' + this.id + ')" value="' + this.id + '" /></td>' +
'<td class="center">' + this.descricao + '</td>' +
'<td class="center">' + this.descCategoria + '</td>' +
'<td class="center">' + this.descCaracteristica + '</td>' +
'<td class="center">' + this.descMedida + '</td>' +
'<td class="center"><input type="text" id="qtd' + this.id + '" style="width:80px"/></td>' +
'</tr>';
});
document.getElementById("resultJs").innerHTML = str_html;
}
});
}
PHP:
<?php
session_start();
require_once("ProjectIncludes.php");
$service = new ProjetoxItensService();
$consulta = $service->getAll($_GET['idprojeto']);
$retorno = json_encode($consulta);
echo $retorno;
?>
Thanks, guys.
Looks like jQuery is not available using $, try jQuery instead.
Change this line:
$.each(resposta, function(){
to this:
jQuery.each(resposta, function(){

javascript function saying it doesn't exist when it does

I'm trying to call a JavaScript function and then pass the value of the button clicked to that function but even though the function does exist its saying it doesn't and im not sure why. Basically I need to call the powerOn() function when the power on button is clicked and then return the status messages. All I need to know is why it won't call the function so I can make sure I get the basic response.
Also I'm not entirely sure why sortable returns a console error when im following the documentation on http://github.hubspot.com/sortable/api/options/:
ReferenceError: Sortable is not defined vmstatus:123
Use of getPreventDefault() is deprecated. Use defaultPrevented instead. jquery-1.10.2.js:5375
TypeError: powerOn is not a function
Code:
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
$.ajax({
url : "/vmstatus/",
type : "POST",
dataType: "json",
data : {
selected_customer : $("#selected_customer").val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success : function(json) {
$('#table-repeat-data').remove();
setInterval(update, 1000);
var on = '<img src={% static "icons/on2.jpg" %}>'
var off = '<img src={% static "icons/off.jpg" %}>'
$('#table_name').append("<table class='table' id='table-repeat-data' data-sortable><thead><tr><th align='center' data-toggle='tooltip' data-placement='left' title=''> <b>VM Name</b></th><th align='center' data-toggle='tooltip' data-placement='left' title=''><b>PowerState </b> </th><th align='center' data-toggle='tooltip' data-placement='left' title='N'><b>Commands </b></th></tr></thead><tbody>");
for (var index = 0; index < json.vmlist.length; index++) {
var powerOn = '<button type="button" name="PowerOn" id="powerOn" onClick="powerOn()" class="btn btn-primary" value="' + json.vmlist[index][2] + '">Power On</button>';
var powerOff = '<button type="button" name="PowerOff" id="powerOff" class="btn btn-danger" value="' + json.vmlist[index][2] + '">Power Off</button>';
var resetVM = '<button type="button" name="ResetVM" id="ResetVM" class="btn btn-warning" value="' + json.vmlist[index][2] + '">ResetVM</button>';
if(json.vmlist[index][1] == 'poweredOn'){
$('#table-repeat-data').append ('<tr><td id="' + json.vmlist[index][0] + '">' + json.vmlist[index][0] + '</td><td id="' + json.vmlist[index][2] + '1">' + on + '</td><td id="' + json.vmlist[index][2] + '">' + powerOn + ' ' + powerOff + ' ' + resetVM + '</td></tr>');
}else{
$('#table-repeat-data').append ('<tr><td id="' + json.vmlist[index][0] + '">' + json.vmlist[index][0] + '</td><td id="' + json.vmlist[index][2] + '1">' + off + '</td><td id="' + json.vmlist[index][2] + '">' + powerOn + ' ' + powerOff + ' ' + resetVM + '</td></tr>');
}
}
},
error : function(xhr,errmsg,err) {
console.log(xhr.status + ": " + xhr.responseText);
}
});
return false;
});
});
function update(){
$.ajax({
url : "/vmstatus/",
type : "POST",
dataType: "json",
data : {
selected_customer : $("#selected_customer").val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success : function(json) {
var on = '<img src={% static "icons/on2.jpg" %}>'
var off = '<img src={% static "icons/off.jpg" %}>'
for (var index = 0; index < json.vmlist.length; index++) {
var powerOn = '<button type="button" name="PowerOn" id="powerOn" onClick="powerOn()" class="btn btn-primary" value="' + json.vmlist[index][2] + '">Power On</button>';
var powerOff = '<button type="button" name="PowerOff" id="powerOff" class="btn btn-danger" value="' + json.vmlist[index][2] + '">Power Off</button>';
var resetVM = '<button type="button" name="ResetVM" id="ResetVM" class="btn btn-warning" value="' + json.vmlist[index][2] + '">ResetVM</button>';
if(json.vmlist[index][1] == 'poweredOn'){
var get_element_id = json.vmlist[index][2] + '1';
document.getElementById(json.vmlist[index][0]).innerHTML = json.vmlist[index][0];
document.getElementById(get_element_id).innerHTML = on;
document.getElementById(json.vmlist[index][2]).innerHTML = powerOn + ' ' + powerOff + ' ' + resetVM;
}else{
var get_element_id = json.vmlist[index][2] + '1';
document.getElementById(json.vmlist[index][0]).innerHTML = json.vmlist[index][0];
document.getElementById(get_element_id).innerHTML = off;
document.getElementById(json.vmlist[index][2]).innerHTML = powerOn + ' ' + powerOff + ' ' + resetVM;
}
}
},
error : function(xhr,errmsg,err) {
console.log('Bad');
console.log(xhr.status + ": " + xhr.responseText);
}
});
}
function powerOn() {
console.log('powerOn');
console.log(this.val());
$.ajax({
url : "/vmstatus/",
type : "POST",
dataType: "json",
data : {
selected_vm : $(this).val(),
username : '{{user_name}}',
ip_address: '{{ip}}',
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success : function(json) {
console.log(json.server_response);
},
error : function(xhr,errmsg,err) {
console.log('Bad');
console.log(xhr.status + ": " + xhr.responseText);
}
});
}
Sortable.init();
var dataTable;
dataTable = document.querySelector('#table-repeat-data');
Sortable.initTable(dataTable);
</script>
Try changing the name of your function, or changing the name of your variable of the same name. It's possible that it is getting confused as to which one you actually mean due to scope.
var powerOn = '<button type="button" name="PowerOn" id="powerOn" onClick="powerOn()" class="btn btn-primary" value="' + json.vmlist[index][2] + '">Power On</button>';
function powerOn() {...}
which one is powerOn? They both are. It's possible that your function is later overridden to a string value and then it is no longer valid to try and call it like it was a function.

jQuery Ajaxcall crashing all browsers

I have a (heavy) function that fetches some data from php/sql and then render it in html. When I load the page for the first time I call this function and everything is fine. When I click on a button I call this function also after an successfull other ajax call, but then my browsers freezes and crashes. I get in Firefox and Chrome an error (page unresponsive).
Here the (heavy)function:
function getMinerAttributesByType(type) {
$.ajax({
type : "POST",
url : "/app/ajax/DataminerAjax.php",
dataType: "json",
timeout : 8000,
data : {getMinerAttributesByType:type}
}).success(function(json){
$tableConfigured = $("#keywordsgroupsConf tbody");
$tableConfigured.html("");
$tableUnconfigured = $("#keywordsgroups tbody");
$tableUnconfigured.html("");
$.each(json, function(key, value){
var $table;
if (value.configured == 0) {
$table = $tableUnconfigured;
} else {
$table = $tableConfigured;
}
$table.append('<tr>' +
'<td>' + value.name + '</td>' +
'<td><button class="btn btn-info" data-toggle="collapse" data-target="#'+ value.id+'-subs" data-id="'+ value.id +'" data-init="0">Config</button></td>' +
'</tr>' +
'<tr class="dataset">' +
'<td colspan="2" class="subrow">' +
'<div style="background:#eee;" class="accordian-body collapse" id="'+ value.id+'-subs">' +
'<table style="margin-bottom: 10px;" class="table" id="table-' + value.id + '" data-id="' + value.id + '">'+
'<tbody>' +
'</tbody>' +
'</table>'+
'<div style="margin-left:10px;" class="input-append">'+
'<input type="text" placeholder="Keywordgroup name">'+
'<button class="btn btn-create-keywordgroup" data-id="' + value.id + '"><i class="icon icon-plus"></i> Add</button>'+
'<button class="btn btn-success btn-mark-as-c" data-id="' + value.id + '"><i class="icon-white icon-check"></i> Mark as configured</button>' +
'</div>' +
'</div>' +
'</td>'+
'</tr>');
});
});
}
Here the function that call the function and crashes afterwards:
$(document).on("click", ".btn-mark-as-c", function(){
if (confirm("Are you sure you want to mark this attribute as configured?")) {
$this = $(this)
var id = $this.attr("data-id");
$.ajax({
type : "POST",
url : "/app/ajax/DataminerAjax.php",
dataType: "json",
data : {updateMinerAttributeState:id, state:1}
}).success(function(json){
if (json.status == "success") {
// crashes here in this call of the heavy function
getMinerAttributesByType(1);
} else {
alert("There was an error!");
}
});
}
});
Someone a pointer?
I dont have 50 rep so I cant comment yet buuuut, couldn't you bust out that chunk of HTML formatting to a PHP document, and then use the AJAX to call the PHP and return the result? Then use $table.append(result)?
Ex)
<script type="text/javascript">
jQuery(document).on('click', '.menuItem', function()
{
event.preventDefault();
var mainCategory = $(this).attr('id').split('xx')[0];
$.ajax({
url: '/php/SubMenuBar.php', <----- Access the PHP file.
data: {
MainCategory: mainCategory, <---- Parameters for the PHP file (declared using $_GET() in the PHP file)
},
success: function(result) <--- Result becomes the output from the PHP file
{
$table.append(result);
}
});
Instead of appending the rows to the DOM one at a time, concatenate them into a string and then add them all at once.
function getMinerAttributesByType(type) {
$.ajax({
type : "POST",
url : "/app/ajax/DataminerAjax.php",
dataType: "json",
timeout : 8000,
data : {getMinerAttributesByType:type}
}).success(function(json){
var $tableConfigured = $("#keywordsgroupsConf tbody");
var $tableUnconfigured = $("#keywordsgroups tbody");
var rowsConfigured = '', rowsUnconfigured = '';
$.each(json, function(key, value){
var row = '<tr>' +
'<td>' + value.name + '</td>' +
'<td><button class="btn btn-info" data-toggle="collapse" data-target="#'+ value.id+'-subs" data-id="'+ value.id +'" data-init="0">Config</button></td>' +
'</tr>' +
'<tr class="dataset">' +
'<td colspan="2" class="subrow">' +
'<div style="background:#eee;" class="accordian-body collapse" id="'+ value.id+'-subs">' +
'<table style="margin-bottom: 10px;" class="table" id="table-' + value.id + '" data-id="' + value.id + '">'+
'<tbody>' +
'</tbody>' +
'</table>'+
'<div style="margin-left:10px;" class="input-append">'+
'<input type="text" placeholder="Keywordgroup name">'+
'<button class="btn btn-create-keywordgroup" data-id="' + value.id + '"><i class="icon icon-plus"></i> Add</button>'+
'<button class="btn btn-success btn-mark-as-c" data-id="' + value.id + '"><i class="icon-white icon-check"></i> Mark as configured</button>' +
'</div>' +
'</div>' +
'</td>'+
'</tr>';
if (value.configured == 0) {
rowsUnconfigured += row;
} else {
rowsConfigured += row;
}
});
$tableConfigured.html(rowsConfigured);
$tableUnconfigured.html(rowsUnconfigured);
});
}

Categories