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

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?

Related

Codigniter Javascript nested Jquery error

My requirnment is if data1[count1].result_type > 0 then the td will be a drop down list from a datatable. Nut is i try this, the output is like this, all the required options are comming to a single selectbox insted of the relevent row. And the result comes to the very last row.
The desired result would be two dropdowns at the last two rows. The wanted result options all together in the one dropdown. How can I solve this?
$('#bill_no_search').click(function() {
{
$("#data_table_one tbody").html("");
var barcode = $('#barcode_no').val();
$.ajax({
url: "<?php echo base_url('index.php/Lab_and_lab_office/get_barcode_to_bill_no'); ?>",
data: {
barcode: barcode
},
method: "POST",
dataType: "JSON",
success: function(data) {
var bill_no = data.bill_no;
console.log(bill_no)
$.ajax({
url: "<?php echo base_url('index.php/Lab_and_lab_office/resulting'); ?>",
data: {
bill_no: bill_no
},
method: "POST",
dataType: "JSON",
success: function(data) {
for (var count = 0; count < data.length; count++) {
var element_id = data[count].element_id;
var ct = 'screen' + count + '';
var bt = 'td' + count + ''
var result = 'result' + count + ''
$('#data_table_one tbody').append(
'<tr>' +
'<td >' + (count + 1) + '</td>' +
'<td >' + data[count].billing_element_result_id + '</td>' +
'<td >' + data[count].bill_no + '</td>' +
'<td >' + data[count].processor_id + '</td>' +
'<td >' + data[count].test_processor_display_name + '</td>' +
'<td >' + data[count].test_code + '</td>' +
'<td >' + data[count].test_details + '</td>' +
'<td contenteditable=true id="result' + count + '">' + data[count].result + '</td>' +
'<td id="td' + count + '" contenteditable=true><select id="screen' + count + '" style="display:none"></select></td>' +
'<td contenteditable=true id="resultcell">' + data[count].result + '</td>' +
'</tr>'
);
console.log(ct)
$.ajax({
url: "<?php echo base_url('index.php/Lab_and_lab_office/get_result_type'); ?>",
data: {
element_id: element_id
},
method: "POST",
dataType: "JSON",
success: function(data1) {
for (var count1 = 0; count1 < data1.length; count1++) {
if (data1[count1].result_type > 0) {
document.getElementById(ct).style.display = "block";
$('#' + ct + '').append(
'<option>' + data1[count1].result_options + '</option>'
);
document.getElementById(bt).contentEditable = "false";
document.getElementById(result).contentEditable = "false";
}
console.log(ct)
}
}
})
}
}
})
}
})
}
})

how to change one button based on value

I want to change my ajax button based on if else condition. Like if status is 1 then it will show just active button otherwise it just show the inactive button. I have two buttons. I cant find the logic where I actually put my if else condition. My code is:
function showAllArticle(status = "") {
//alert(status);
$.ajax({
//cache: false,
//headers: { "cache-control": "no-cache" },
type: 'ajax',
method: 'post',
data: {
status: status
},
url: '<?php echo base_url() ?>Article/showAllUser',
async: true,
dataType: 'json',
//cache: false,
success: function(data) {
var html = '';
var i;
for (i = 0; i < data.length; i++) {
//(data[i].status);
html += '<tr>' +
'<td>' + data[i].id + '</td>' +
'<td>' + data[i].username + '</td>' +
'<td>' + data[i].email + '</td>' +
'<td>' +
// '{% if data[i].status == 1 %}'
'Active' +
//#if(data[i].status == 1)
//'{% else %}'
'Inactive' +
//'{% endif %}'
/* '</td>' +
'<td>'+
'+#if(data[i].status == 1)+'
'tseting'+
'+#elseif(data[i].status == 0)+'
'debug'+
'+#endif+'
'</td>'+*/
'</tr>';
}
$('#showdata').html(html);
},
error: function() {
alert('Could not get Data from Database');
}
});
}
You must apply the if condition based on JS, not on the template language you are using as JS is executed on the user end.
You must do something similar do this:
html += '<tr>';
html += '<td>' + data[i].id + '</td>';
html += '<td>' + data[i].username + '</td>';
html += '<td>' + data[i].email + '</td>';
html += '<td>';
if (data[i].status == 1) {
html += 'Active';
} else if(data[i].status == 12) {
//...
} else {
html += 'Inactive' +
}
/* '</td>' +
'<td>'+
'+#if(data[i].status == 1)+'
'tseting'+
'+#elseif(data[i].status == 0)+'
'debug'+
'+#endif+'
'</td>'+*/
html += '</tr>';

Change color related on value

I have table values populated from back-end
Here is js function that doing it.
function AllProposals() {
let getProposalsUrl = '/proposals/index';
$.ajax({
url: getProposalsUrl,
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
processData: false,
success: function (data) {
$("#proposals").empty();
var list = data;
for (var i = 0; i <= list.length - 1; i++) {
var tableData = '<tr>' +
'<td class="proposalId">' +
list[i].Id +
'</td>' +
'<td > ' +
list[i].Project +
'</td>' +
'<td > ' +
moment(list[i].DateFrom).format('DD/MM/YYYY') + "--" + moment(list[i].DateTo).format('DD/MM/YYYY') +
'</td>' +
'<td> ' +
list[i].WorkTime + "--" +list[i].WorkTimeTo +
'</td>' +
'<td > ' +
list[i].Quantity+
'</td>' +
'<td> ' +
list[i].Service +
'</td>' +
'<td> ' +
list[i].Price +
'</td>' +
'<td> ' +
list[i].Status +
'</td>' +
'</tr>';
$('#proposals').append(tableData);
}
}
})
}
It working great.
Bu It need to check this value on flight
'<td> '+list[i].Status+'</td>' +
And if it is "Rejected" change text color to red.
How I can do this correctly?
Thank's for help.
Assuming that this code will need some refactoring if you will need to reuse the return data of the ajax call and in general it is not good looking, I would do as follows:
'<td'+ (list[i].Status == 'Rejected' ? ' style="color:red;"' : '') +'> ' +
list[i].Status +
'</td>' +
Edit
If in future you will need to assign different colors based on the content of list[i].Status, I suggest to create a content-to-color lookup table:
let contentToColor = {
"Rejected": "red",
"Success": "green",
"Warning": "yellow"
};
and then:
'<td'+ (contentToColor[list[i].Status] !== 'undefined' ? ' style="color: '+ contentToColor[list[i].Status] +';"' : '') +'> ' +
list[i].Status +
'</td>' +
The way of checking the existence of the variable may be wrong, I don't remember how it is done in JS, but you get the concept.
Anyway, I would suggest to refactor the code by separating the presentation code and the domain code. You will save yourself by the ugly code I wrote above. I had to read it 10 times for checking if the quotes were good.
You can use a switch to get the status and set the color base on what you get and pass it to a variable.
Example
<script>
function AllProposals() {
let getProposalsUrl = '/proposals/index';
$.ajax({
url: getProposalsUrl,
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
processData: false,
success: function (data) {
$("#proposals").empty();
var list = data;
for (var i = 0; i <= list.length - 1; i++) {
var mycolor = "";
switch (list[i].Status) {
case "Approved":
mycolor = "style="color:green";
break;
case "Rejected":
mycolor = "style="color:red";
//Add more if needed
}
var tableData = '<tr>' +
'<td class="proposalId">' +
list[i].Id +
'</td>' +
'<td > ' +
list[i].Project +
'</td>' +
'<td > ' +
moment(list[i].DateFrom).format('DD/MM/YYYY') + "--" + moment(list[i].DateTo).format('DD/MM/YYYY') +
'</td>' +
'<td> ' +
list[i].WorkTime + "--" +list[i].WorkTimeTo +
'</td>' +
'<td > ' +
list[i].Quantity+
'</td>' +
'<td> ' +
list[i].Service +
'</td>' +
'<td> ' +
list[i].Price +
'</td>' +
'<td' + mycolor +'> ' +
list[i].Status +
'</td>' +
'</tr>';
$('#proposals').append(tableData);
}
}
})
}
</script>
You can use alter the style attribute using jQuery's .attr method (http://api.jquery.com/attr/)
if(status=="rejected"){
$(.elementclass).attr("style","color:red");
}

How to set Onclick dynamic to generated rows?

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.

Problems in Binding To Dynamic Table

I worked on this sample for 3 days strucked at last step!! Please some one help me!!
Any Help is appreciable!!
I am loading a dynamic table, i want to attach a grid on a column. I created a function for binding jqgrid. So when ever i am binding a table i am calling this function with a parameter,
The problem here is if i give the parameter directly it is working , but if i want to load it automatically it is not working.
I will explain below with code:
function bindData() {
$.ajax({
type: "POST",
url: location.pathname + "/getData",
data: "{}",
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function (response) {
var msg = eval('(' + response.d + ')');
if ($('#tblResult').length != 0) // remove table if it exists
{ $("#tblResult").remove(); }
var table = "<table class='tblResult' id=tblResult><thead> <tr><th>Name</th><th>SurName</th><th>Email</><th>Mobile</th><th>Address</th><th>Actions</th><th>image</th><th>Country</th><th>State</th><th>Gender</th><th>Add.Mobile</th></thead><tbody>";
for (var i = 0; i <= (msg.length - 1); i++) {
var row = "<tr>";
row += '<td>' + msg[i].Name + '</td>';
row += '<td>' + msg[i].SurName + '</td>';
row += '<td>' + msg[i].Email + '</td>';
row += '<td>' + msg[i].Mobile + '</td>';
row += '<td>' + msg[i].Address + '</td>';
row += '<td><img id="im" src="/User_Registration1/images/edit.png" title="Edit record." onclick="bindRecordToEdit(' + msg[i].EmployeeId + ')" /> <img src="/User_Registration1/images/delete.png" onclick="deleteRecord(' + msg[i].EmployeeId + ')" title="Delete record." /></td>';
row += '<td><img class="img" src=' + msg[i].FileName + ' alt="--NO IMAGE--"/></td>';
row += '<td>' + msg[i].Country + '</td>';
row += '<td>' + msg[i].StateName + '</td>';
row += '<td>' + msg[i].Gender + '</td>';
row += '<td style="width:250px;height:120px;"><table id="tblSub' + msg[i].Name + '"></table><script> $(document).ready(function () { BindGrid("AjjiAjji");});</script></td>';
row += '</tr>';
table += row;
}
table += '</tbody></table>';
$('#divData').html(table);
$("#divData").slideDown("slow");
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
}
see the last column in which i am attaching a grid view by calling a javascript function.
js function:
function BindGrid(user) {
$(document).ready(function () {
$("#tblSub"+user).jqGrid({
loadError: function (xhr, status, error) {
alert('load:' + error);
},
url: 'Fetch.aspx?filter=' + user + '',
data: "{}",
datatype: 'json',
colNames: ['Name', 'Mobile'],
colModel: [
{
name: 'User',
index: 'User',
width: 100,
align: "left",
editable: true,
size: 80
},
{
.
.
.
So if i pass the BindGrid("AjjiAjji") it is working fine, But i want to load the grid automatically like BindGrid('+msg[i].Name+') , It is Showing Error "ReferenceError: AjjiAjji is not defined"
I think you are forgetting to add double quotes and the result whould be BindGrid (AjjAjj). try this:
BindGrid("'+msg[i].Name+'")
this should work fine
I think that problem is that the time you are attaching jqGrid to "$("#tblSub"+user)" is not present in DOM.
You should call BindGrid function only after $('#divData').html(table); which is adding table into DOM.
So that jqGrid can properly work.

Categories