I wrote the following code creating a popup with dynamic added content. Now I want to delete these added items or edit them, but it didn't seem to fire an event clicking one of those buttons (btnLSM_Remove + btnLSM_Edit). Any clues why it is so? btnLSM_Add and btnLSM_Okay work the same way and they do work...
function ListManagementDialog(obj, dialogTitle, dialogText, listDelimiter, btnNames) {
if (!$.isArray(btnNames)) {
return false;
}
if (dialogConfirmed) {
return false;
}
btns[btnNames[0]] = function () {
$(this).dialog('close');
dialogConfirmed = true;
if (obj) {
obj.click();
}
};
btns[btnNames[1]] = function () {
$(this).dialog('close');
};
$('body').append(String.Format('<div id="divLSM_Dialog" title="{0}"><p>{1}</p>' +
'<button id="btnLSM_Add" class="btnAdd" type="button" role="button" aria-disabled="false" title="Hinzufügen" />' +
'<input id="txbLSM_Emailadresse" class="text ui-widget-content ui-corner-all" type="text" name="txbLSM_Emailadresse" style="display:none;">' +
'<button id="btnLSM_Okay" class="btnOkay" type="button" role="button" aria-disabled="false" title="Übernehmen" style="display:none;" />' +
'<br /><br />' +
'<table id="tblLSM_Items" class="ui-widget ui-widget-content">' +
'<thead>' +
'<tr class="ui-widget-header ">' +
'<th>Emailadresse</th>' +
'<th />' +
'</tr>' +
'</thead>' +
'<tbody />' +
'</table>' +
'</div>', dialogTitle, dialogText));
$('#btnLSM_Add').click(function () {
$('#txbLSM_Emailadresse').val('');
$('#txbLSM_Emailadresse').show();
$('#btnLSM_Okay').show();
$('#txbLSM_Emailadresse').focus();
});
$('#btnLSM_Okay').click(function () {
$('#tblLSM_Items tbody').append('<tr>' +
'<td>' + $('#txbLSM_Emailadresse').val() + '</td>' +
'<td>' + '<button id="btnLSM_Remove" class="btnRemove" type="button" role="button" aria-disabled="false" title="Entfernen" />' + '<button id="btnLSM_Change" class="btnEdit" type="button" role="button" aria-disabled="false" title="Ändern" />' + '</td>' +
'</tr>');
$('#txbLSM_Emailadresse').hide();
$('#btnLSM_Okay').hide();
});
$('#btnLSM_Remove').click(function () {
alert("hohoho"); //no alert-popup
});
$('#btnLSM_Change').click(function () {
alert("hohoho"); //no alert-popup
});
$('#divLSM_Dialog').dialog({
modal: true,
resizable: false,
draggable: true,
width: 600,
height: 300,
close: function (event, ui) {
$('body').find('#divLSM_Dialog').remove();
},
buttons: btns
});
return dialogConfirmed;
}
Your btnLSM_Remove button doesn't exist when you call
$('#btnLSM_Remove').click(function () {
So the $('#btnLSM_Remove') collection is empty and the handler is added to nothing.
You may use the on function:
$('#divLSM_Dialog').on('click', '#btnLSM_Remove', function () {
to register an handler that will apply to a button appearing after the delegation definition.
EDIT :
In jQuery 1.6.2, you may use live :
$('#btnLSM_Remove').live('click', function () {
Related
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...).
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.
I have a JS function that loads the comments of a certain answer. The idea is to call an API function and to return the comments.
The problem is that everytime I press the button it loads the comments, the same exact comments.
I want something that after you press comment, you cannot load more comments. I though stopPropagation would do the trick but nothing happened.
Is it possible to when I press the Comment button after I call it, it closes my #showarea
<div class="post-button clearfix">
<div class="post-button clearfix">
<button class="btn icon-chat show-textarea" title="Add a comment on this answer" type="button" data-answer="{$answer['publicationid']}">Comment</button>
<div class="textarea">
{include file="comment_form.tpl"}
</div>
</div>
</div>
comment_form.tpl
$('.comment-form').hide();
var commentsFetched = false;
$("body").on("click", ".show-textarea", function(){
if (commentsFetched) { // check the flag
return;
}
$.getJSON("/controller/api/comments/comment.php", {
answerid : answerid
}, function (data) {
commentsFetched = true;
$.each(data, function(i, comment) {
console.log(comment);
$('.comment-form').append('<article class="tweet-data">' +
'<div class="comment-items">' +
'<div class="qa-c-list-item hentry comment" id="c3574">' +
'<div class="asker-avatar">' +
'<a>' +
'<img width="40" height="40" src="' +
comment.user_photo +
'"></a>' +
'</div>' +
'<div class="qa-c-wrap">' +
'<div class="post-button">' +
'<button name="" onclick="" class="btn icon-flag" title="Flag this comment as spam or inappropriate" type="submit">flag</button>' +
'<button name="" class="btn icon-answers" title="Reply to this comment" type="submit">reply</button>' +
'</div>' +
'<span class="qa-c-item-meta">' +
'commented' +
' 1 day' +
' ago' +
' by ' +
'<a style="display: inline" href="" class="qa-user-link url nickname">' +
comment.username +
'</a> ' +
'<span class="qa-c-item-who-points"> ' +
'<span class="qa-c-item-who-points-pad">(</span><span class="qa-c-item-who-points-data">140</span><span class="qa-c-item-who-points-pad"> points)</span> ' +
'</span> ' +
'</span> ' +
'</span> ' +
'<div class="qa-c-item-content" style="color: #2d2727; font-size: 13px"> ' +
'<a name="3574"></a><div class="entry-content">' +
comment.body +
'</div> ' +
'</div> ' +
'</div> <!-- END qa-c-item --> ' +
'</div> ' +
'</div>');
});
});
$('.comment-form').show();
});
$("body").on("click", ".textarea-ok, .textarea-cancel", function(){
commentsFetched = false;
$('.comment-form').hide();
});
set a flag to know if you already fetched the comments.
var commentsFetched = false;
$("#showarea").click(function() {
if (commentsFetched) { // check the flag
return;
}
$.getJSON("/controller/api/comments/comment.php", {
answerid : answerid
}, function (data) {
commentsFetched = true; // set the flag
$.each(data, function(i, comment) {
...
You should probably disable the button to give your users a visual indication no more comments can be loaded
I want a button to call a function onclick but it does not. I tried ng-click which does not work. But when I try onclick it says my function is undefined. How can I accomplish that?
Thank you.
Function to customize the tooltip:
function createCustomHTMLContent(img, evtTime, cmname, evt, cust, serv, descr, duration) {
var html ='<script type="text/javascript" src="validate.js"></script><div class="myclass" style="padding:5px 5px 5px 5px;width: 300px;height: 350px;">' +
'<img src="'+img+'" style="width:285px;height:230px">' +
'<table>'+'<tr>'+
'<td><strong>Date :</strong></td>' +
'<td><b>'+evtTime+'</b></td>' + '</tr>' + '<tr>' +
'<td><strong>Event Type :</strong></td>' +
'<td><b>'+evt+'</b></td>' + '</tr>' + '<tr>' +
'<td><strong>Customer :</strong></td>' +
'<td><b>'+cust+'</b></td>' + '</tr>' + '<tr>' +
'<td><strong>Severity :</strong></td>' +
'<td><b>'+serv+'</b></td>' + '</tr>' + '<tr>' +
'<td><strong>Description :</strong></td>' +
'<td><b>'+descr+'</b></td>' + '</tr>' + '<tr>' +
'<td><form ng-form-commit name="myForm" action="" onsubmit="testfunt()" target="dummyframe" method="post" novalidate><div class="row"><div class="text-center"><button ng-click="timeline.heyfun();">View Video</button></div></form></div></td></tr></table>';
return html;
}
function addData() {
rows.push([""+cmname, ""+id,createCustomHTMLContent(thumbpath, evtTime, cmname, evt, cust, serv, descr, 0),new Date(datetime), new Date(datetime1),'color:'+colors[serv]]);
tc.dataTable.addRows(rows);
var options = {
width : $scope.width,
height: $scope.height,
title: 'Timeline',
hAxis: {
title: 'Date',
format:'yy-MM-dd\n\nHH:mm:ss'
},
timeline: { //colorByRowLabel: true,
showBarLabels: false},
// backgroundColor: '#ffd',
colors: grapghcols,
// This line makes the entire category's tooltip active.
focusTarget: 'category',
// Use an HTML tooltip.
tooltip: { isHtml: true,}
};
tc.chart.draw(tc.dataTable, options);
$compile(tc.dataTable)($scope);
}
There is alot of code. SO i tried to include the relevant snippets needed. Please let me know if you need more details.
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);
});
}