Update Javascript object with code from AJAX request - javascript

I have a function to create a new object 'dialogBox' and then perform an an AJAX request and add/remove buttons from it. The function works fine as part of my main HTML page using the following code:
var dialog1 = new dialogBox(500, 250, "Add Note","dialog_add_note.php?job_id=" + jobdetails[1]);
dialog1.addButton("Save","Right");
I have numerous (20+) dialog boxes, and therefore want update the content of the buttons after the box has been initialised.
I perform an AJAX request which updates the HTML within the dialog box. The following script is returned as part of this request:
dialog1.addButton("Save","Right");
I get an error stating that dialog1 is now undefined.
Is there a way which I can continue to update the object using javascript code which has been passed by the AJAX request? I had done this prevously without using objects, but it was becoming unmanageable.
Thanks in advance
The AJAX request is performed when the object is initialised. See function below:
function dialogBox(w, h, title, link) {
this.w=w;
this.h=h;
this.title=title;
this.link=link;
//Strip spaces from title to form ID
var id = 'dialog_' + title.replace(" ","_");
//Add dialog box div
$( "body" ).append( "<div id='" + id + "' title='" + title + "'></div>");
//Create dialog box
$( '#' + id ).dialog({
autoOpen: true,
height: h,
width: w,
modal: true,
resizable: false,
buttons: {
Cancel: function() {
$('#' + id).remove();
}
},
close: function() {
$('#' + id).remove();
}
});
//Set buttonSet and remove all buttons
this.buttonSet = $('#' + id).parent().find('.ui-dialog-buttonset');
this.buttonSet.empty();
//Loading icon
$('#' + id).html("<div style='text-align:center;'><br><img src='../images/ajaxloader.gif' alt='Loading...'></div>");
//Set initial content of dialog box
$.get('ajax/' + link, function(data) {
$('#' + id).html(data);
});
//Function to update content of dialog box
this.update=update;
function update(link) {
$.get('ajax/' + link, function(data) {
$('#' + id).html(data);
});
}
//Clear button
this.clearButton = clearButton
function clearButton(name) {
var tempName = name.replace(" ","_");
$('#' + id + '_button_' + tempName).remove();
}
//Clear buttons
this.clearButtons = clearButtons
function clearButtons() {
this.buttonSet.empty();
}
//Add Button
this.addButton = addButton
function addButton(name, position) {
var tempName = name.replace(" ","_");
newButton = $("<button id='" + tempName + "' style='float:" + position + ";'>" + name + "</button>");
newButton.button();
this.buttonSet.append(newButton);
}
//Close Dialog
this.close=close
function close() {
$('#' + id).remove();
}
}

Related

Not able to understand how tag value is included from jsp page to js file

I am facing a problem where I have button in jsp page if i click it then it opens the dialogue and for the first time I am opening it , it shows the title of the dialogue box but from the second time onwards it doesnt show the title of dialogue.. I just started working on javascript and jsp , here I need a little help to understand where this value is coming from ,
**if($('#add-meeting-time').size() == 0)
$('body').append('<div id="add-meeting-time" />');**
How #add-meeting-time tag value is coming from jsp and why it is fetching the tag value add-meeting-time from jsp first time and not from the second time. I have added the code below.
please have a look and help
thanks in advance.
function addMeetingTime(caseId, passedds) {
showOverlay();
$.ajax({
url : 'case/RepairPro_addInputAgreeMeetingEvent?passedds='+passedds,
type : 'get',
data : 'cid=' + caseId + "&t=" + Math.random(),
success : function(data) {
if($('#add-meeting-time').size() == 0)
$('body').append('<div id="add-meeting-time" />');
$('#add-meeting-time').html(data);
$( "#add-meeting-time" ).dialog({
autoOpen: false,
modal: true,
width:650,
buttons: {
action: {
text: getText('save'),
click: function() {
disableDialogButton();
$('#add-meeting-time form').submit();
}
},
cancel: {
text: getText('cancel'),
click: function() {
$( this ).dialog( "close" );
}
}
},
create: function() {
var datepickerSettings = {minDate: 0};
if (getConfig('isDisplayTimezone')) {
datepickerSettings = {}
}
if(getConfig('isCalendarModularEnabled')) {
if(localMember.myrole > parseInt(getGlobal('AUTH2'))) {
$(this).parent().find('.ui-dialog-title').before($("<a href='javascript:void(0);' onclick='addMeetingTimeCalendar(\"" + passedds + "\", " + caseId + ");' title=\"" + getText('calendar_view') + "\" style='float:left; margin-right:1em;' class='ui-icon extra-dialog-button'></a>")
.button({icons:{primary: "ui-icon-calendar"},text: false}));
}
else {
$(this).parent().find('.ui-dialog-title').before($("<a href='javascript:void(0);' onclick='addPersonalMeetingTimeCalendar(\"" + passedds + "\", " + caseId + ");' title=\"" + getText('calendar_view') + "\" style='float:left; margin-right:1em;' class='ui-icon extra-dialog-button'></a>")
.button({icons:{primary: "ui-icon-calendar"},text: false}));
}
}
$(this).find('.datepicker').datetimepicker(datepickerSettings);
showTaskError(this, 'refreshCaseMessagesPage()');
initTeamMemberSelect();
},
open: function() {
$('select[id=add-meeting-member] option:eq(1)').attr('selected', 'selected');
$('select[id=add-meeting-member] option:eq(0)').attr('selected', 'selected');
},
close: function() {
$( this ).dialog( "destroy" ).remove();
}
});
$( '#add-meeting-time' ).dialog( 'open' );
}
});
}

How to open Bootstrap modal pop-up one after other?

In mvc application, I have a HTML table on which data is created on load using Ajax. This HTML table consists of N number of records, I have applied Pagination to the table using Jquery so that only 10 records are added to a single page on the table.
Now the first column of the html table is checkbox which means that if I select the checkbox in the header all the records in the particular page of the table would be selected. I have few buttons on the top which does certain functionalities among them is a delete button which deletes all the records which are selected from the table. Now the problem is that for each records a Modal Popup should show up asking "Do you want to delete the records of {somename}?". I have a confirm button and a cancel button.
On click of "Confirm" the particular record details would be deleted and then again a new pop-up should display asking confirmation to delete the records. Like wise if I click Cancel then the current popup should be closed and new one should open asking confirmation to delete the records.
Following is the code that I did
//Create a modal popup
function BootstrapModalPopUp(modalId, ButtonConfirmID, ButtonCancelID, ButtonText, modalTitle, modalBody) {
var popUpContent = '<div class="modal fade" id="myModal' + modalId + '" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">'
+ '<div class="modal-dialog" role="document">'
+ '<div class="modal-content">'
+ '<div class="modal-header">'
+ '<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>'
+ '<h4 class="modal-title" id="myModalLabel">' + modalTitle + '</h4>'
+ '</div>'
+ '<div class="modal-body">'
+ '<h4 class="modal-title" id="myModalLabel">' + modalBody + '</h4>'
+ '</div>'
+ '<div class="modal-footer">';
if (ButtonConfirmID != '') {
popUpContent += '<button id="btn' + ButtonConfirmID + '" type="button" class="btn btn-primary" data-dismiss="modal">Confirm</button>'
+ '<button id="btn' + ButtonCancelID + '" type="button" onclick="modalpopupcancel()" class="btn btn-primary" data-dismiss="modal">' + ButtonText + '</button>'
}
else {
popUpContent += '<button id="btn' + ButtonCancelID + '" type="button" onclick="modalpopupcancel()" class="btn btn-primary" data-dismiss="modal">' + ButtonText + '</button>'
}
+ '</div></div></div></div>';
$('#myModalPopups').append(popUpContent);
}
//On click of the button
function EmailConfirmationSubmit(buttonName) {
$('#' + buttonName).click(function () {
//Getting the number of CheckBox
var $chkboxes = $('#tblMemberList').find("tr input[type='checkbox']:checked");
//Getting the ID (checked value) from the CheckBox and storing in Array
var checkBoxVals = $chkboxes.map(function () { return $(this).attr('id'); }).toArray();
//remove the first element of the checkbox. This is the header of the checkbox which we dont need to show the pop up for
if ($.inArray('memberListHeaderCheckBox', checkBoxVals) > -1) {
checkBoxVals.splice($.inArray("memberListHeaderCheckBox", checkBoxVals), 1);
}
var ModalIdBeforeCreation = 'DeleteConfirmation';
var ModalConfirmIDBeforeCreation = '_DeleteConfirm';
var ModalCancelIDBeforeCreation = '_DeleteCancel';
//Checking the Array whether it is not empty
if (!isArrayEmpty(checkBoxVals)) {
//Loop through each selected checkbox
checkBoxVals.forEach(function (CheckBox) {
//Get id and name of the check box. The name is the pension ID
var CheckBoxID = $("#" + CheckBox).val();
var CheckBoxName = $("#" + CheckBox).attr('name').toString();
var ModalId = ModalIdBeforeCreation + CheckBoxID;
var ModalConfirmID = ModalConfirmIDBeforeCreation + CheckBoxID;
var ModalCancelID = ModalCancelIDBeforeCreation + CheckBoxID;
var ModalMessage = 'Do you want to delete the records for the member ' + CheckBoxName + ' ?'
$("#"+ModalId).remove();
//Create dynamic pop up based on each Pension ID which is selected on Html Table
BootstrapModalPopUp(ModalId, ModalConfirmID, ModalCancelID, 'Cancel', 'Delete Confirmation', ModalMessage);
});
var checkBoxID = $('#' + checkBoxVals[0]).attr('id');
CreateAlertsForActions(ModalIdBeforeCreation,ModalConfirmIDBeforeCreation,ModalCancelIDBeforeCreation,checkBoxVals,checkBoxID,PageActions.OnDelete,Controllers.CommutedPensions,"OnDelete");
}
else {
//do something
}
});
}
//Create alerts
function CreateAlertsForActions(ModalIdBeforeCreation,ModalConfirmIDBeforeCreation,ModalCancelIDBeforeCreation,CheckBoxArray,checkBoxID,PageAction,ControllerName,ActionName)
{
var checkBoxValue = $('#' + checkBoxID).val();
var index = CheckBoxArray.indexOf(checkBoxID);
//Again get the new ID
checkBoxID = $('#' + CheckBoxArray[index+1]).attr('id');
if(checkBoxValue != undefined)
{
var ModalId = ModalIdBeforeCreation + checkBoxValue;
var ModalConfirmID =ModalConfirmIDBeforeCreation + checkBoxValue;
var ModalCancelID = ModalCancelIDBeforeCreation+ checkBoxValue;
$('#myModal'+ModalId).modal('show');
//On Confirm Click
$('#myModal' + ModalId).on('click', '#btn' + ModalConfirmID, function () {
AjaxRequestToControllerAction(ControllerName,ActionName,PageAction,checkBoxValue);
CreateAlertsForActions(ModalIdBeforeCreation,ModalConfirmIDBeforeCreation,ModalCancelIDBeforeCreation,CheckBoxArray,checkBoxID,PageAction,ControllerName,ActionName);
});
//Popup Cancel button click event
$('#myModal' + ModalId).on('click', '#btn'+ModalCancelID, function () {
CreateAlertsForActions(ModalIdBeforeCreation,ModalConfirmIDBeforeCreation,ModalCancelIDBeforeCreation,CheckBoxArray,checkBoxID,PageAction,ControllerName,ActionName);
});
//Popup close button click event
$('#myModal' + ModalId).on('click', '#btn'+ModalCancelID, function () {
CreateAlertsForActions(ModalIdBeforeCreation,ModalConfirmIDBeforeCreation,ModalCancelIDBeforeCreation,CheckBoxArray,checkBoxID,PageAction,ControllerName,ActionName);
});
//When the mouse is clicked out side of the popup
$('#myModal' + ModalId).on('hidden.bs.modal', function () {
CreateAlertsForActions(ModalIdBeforeCreation,ModalConfirmIDBeforeCreation,ModalCancelIDBeforeCreation,CheckBoxArray,checkBoxID,PageAction,ControllerName,ActionName);
});
}
}
function AjaxRequestToControllerAction(Controller, ActionMethod, Action, CheckBoxValue) {
$.ajax({
//The Url action is for the Method FilterTable and the Controller CurrentYearApplications
//url: '#Url.Action("' + ActionMethod + '", "' + Controller + '")',
url: '/' + Controller + '/' + ActionMethod + '/',
//The text from the drop down and the corresponding flag are passed. Flag represents the Index of the value in the dropdown
data: { ID: CheckBoxValue, PageAction: Action },
contentType: "application/json; charset=utf-8",
//Json data
datatype: 'json',
//Specify if the method is GET or POST
type: 'GET',
//Error function gets called if there is an error in the ajax request
error: function (jq, status, message) {
//Show error
},
//Gets called on success of the Ajax Call
success: function (data) {
//Do things after success
}
});
}
Everything works fine for me, if there are just 4,5 records selected, but when I select around 10 records and choose to delete them, the first 4,5 work fine, then the popup seems to crash.
Any help in this regard or suggestions for alternative methods to follow would be really appreciated.
Thanks in Advance.

assign multiple value to javaScript array object

i have coded jQuery widget, which list all the record title in table which user can select of multiple records but with each record user to need to put value in text box.
now i want to built jQuery or JavaScript array where i can push record with each user click add and remove data if click remove against each button.
i want to push "recordId" & "ComponentSchemeMarks" to javaScript array selectedComponentList
var selectedComponentList = {
componentIndex: "",
componentMark:""
};
$(document).ready(function () {
//click on Confirm Component Scheme
$("#ComponentSchemeTable").on("click", ".k-grid-confirm", function () {
var recordId = $(this).data("id");
var ComponentSchemeMarks = $("#" + recordId + "_CM").val();
alert("recordId " + recordId + " ComponentSchemeMarks " + ComponentSchemeMarks);
//
$(this).hide();
$(this).siblings(".k-grid-input").hide();
$(this).siblings(".k-grid-cancel").hide();
$(this).siblings(".k-grid-Remove").show();
//add data to array//
});
$("#ComponentSchemeTable").on("click", ".k-grid-Remove", function () {
$(this).hide();
$(this).siblings(".k-grid-Add").show();
});
Your selectedComponentList is not an array... I guess you want something like this:
var selectedComponentArray = [];
$(document).ready(function () {
//click on Confirm Component Scheme
$("#ComponentSchemeTable").on("click", ".k-grid-confirm", function () {
var recordId = $(this).data("id");
var ComponentSchemeMarks = $("#" + recordId + "_CM").val();
alert("recordId " + recordId + " ComponentSchemeMarks " + ComponentSchemeMarks);
//
$(this).hide();
$(this).siblings(".k-grid-input").hide();
$(this).siblings(".k-grid-cancel").hide();
$(this).siblings(".k-grid-Remove").show();
//add data to array//
selectedComponentArray.push({ComponentIndex: recordId, ComponentMark: ComponentSchemeMarks});
});
$("#ComponentSchemeTable").on("click", ".k-grid-Remove", function () {
$(this).hide();
$(this).siblings(".k-grid-Add").show();
var recordId = $(this).data("id");
selectedComponentArray = $.grep(selectedComponentArray, function(value) {
return value.ComponentIndex != recordId;
});
});
...
}
Moreover you should give the buttons IDs and use them for binding the click listeners...

preventdefault() not working in IE8

I'm working on a page that makes fairly heavy use of ajax. All the ajax forms appear to be working fine across browsers but one final step on the page is broken in IE8 and below.
Here is a demo page showing the problem: http://jolora.com/~fwm/
To reproduce the issue please fill in the final form (email name etc) - a list of markers will be shown on the map. The 'Request Appointment' button should fire an ajax function but instead it actually submits the form in IE7 and IE8 so it appears preventDefault isn't working.
Here's the relevant jQuery:
// Request appointment
$('#map').on('submit', 'form', function(event) {
event.preventDefault();
var solicitorID = $(this).attr('id');
solicitorRequest(solicitorID,applicationID);
});
function solicitorRequest(requestedSolicitor,currentApplication) {
$.ajax({
url: siteurl + 'wp-admin/admin-ajax.php',
data:{
'action':'do_ajax',
'fn':'request_solicitor',
'solicitor': requestedSolicitor,
'application': currentApplication
},
dataType: 'JSON',
success:function(data){
alert('Please check your email - this success function needs improving');
},
error: function(errorThrown){
alert('error');
//console.log(errorThrown);
}
});
}
The popups are built using Leaflet's bindPopup method http://leafletjs.com/reference.html#popup and here's the structure of the content I insert into the popup:
var popupContentBegin = '<form id="'
+ solicitor.id + '">'
+ '<h3>' + solicitor.name + '</h3>'
+ '<div class="contact-details">'
+ '<span class="addr">' + solicitor.address + '</span>';
var popupContentTel = '';
if(solicitor.telephone != false) {
popupContentTel = '<span class="tel">'
+ solicitor.telephone
+ '</span>';
}
var popupContentEnd = '</div>'
+ '<button type="submit">Request appointment</button>'
+ '</form>';
var popupContent = popupContentBegin + popupContentTel + popupContentEnd;
var marker = L.marker([lat, lng], {icon: solicitorIcon}).bindPopup(popupContent, popupOptions);
Any help would be greatly appreciated! Thanks.
Try changing your selector to:
$(document).on('submit', '#map form', function(event) {...
http://api.jquery.com/live/
EDIT: You need to call this function inside a ready function so that you can be sure the DOM was completely loaded:
$(function () {
// Put code here
});

How to get the value value of a button clicked Javascript or Jquery

I'll try to be as straight to the point as I can. Basically I using jquery and ajax to call a php script and display members from the database. Next to each members name there is a delete button. I want to make it so when you click the delete button, it deletes that user. And that user only. The trouble I am having is trying to click the value of from one delete button only. I'll post my code below. I have tried alot of things, and right now as you can see I am trying to change the hash value in the url to that member and then grap the value from the url. That is not working, the value never changes in the URL. So my question is how would I get the value of the member clicked.
<script type="text/javascript">
$(document).delegate("#user_manage", "pagecreate", function () {
$.mobile.showPageLoadingMsg()
var friends = new Array();
$.ajaxSetup({
cache: false
})
$.ajax({
url: 'http://example.com/test/www/user_lookup.php',
data: "",
dataType: 'json',
success: function (data) {
$.mobile.hidePageLoadingMsg();
var $member_friends = $('#user_list');
$member_friends.empty();
for (var i = 0, len = data.length; i < len; i++) {
$member_friends.append("<div class='user_container'><table><tr><td style='width:290px;font-size:15px;'>" + data[i].username + "</td><td style='width:290px;font-size:15px;'>" + data[i].email + "</td><td style='width:250px;font-size:15px;'>" + data[i].active + "</td><td><a href='#" + data[i].username + "' class='user_delete' data-role='none' onclick='showOptions();'>Options</a></td></tr><tr class='options_panel' style='display:none'><td><a href='#" + data[i].username + "' class='user_delete' data-role='none' onclick='showId();'>Delete</a> </td></tr></table></div>");
}
}
});
});
</script>
<script>
function showId() {
var url = document.URL;
var id = url.substring(url.lastIndexOf('#') + 1);
alert(id);
alert(url);
}
</script>
IDEAS:
1st: I think it would be easier to concatenate an string an later append it to the DOM element. It's faster.
2nd: on your button you can add an extra attribute with the user id of the database or something and send it on the ajax call. When getting the attribute from the button click, use
$(this).attr('data-id-user');
Why don't you construct the data in the PHP script? then you can put the index (unique variable in the database for each row) in the button onclick event. So the delete button would be:
<button onclick = "delete('indexnumber')">Delete</button>
then you can use that variable to send to another PHP script to remove it from the database.
$('body').on('click', 'a.user_delete', function() {
var url = document.URL;
var id = url.substring(url.lastIndexOf('#') + 1);
alert(id);
alert(url);
});
<?php echo $username ?>
Like wise if you pull down users over json you can encode this attribute like so when you create your markup in the callback function:
'<a href="#'+data[i].username+'" data-user-id="'+ data[i].username + '" class="user_delete" data-role="none" >Options</a>'
So given what you are already doing the whole scenerio should look something like:
$(document).delegate("#user_manage", "pagecreate", function () {
$.mobile.showPageLoadingMsg();
var friends = new Array(),
$member_friends = $('#user_list'),
// lets jsut make the mark up a string template that we can call replace on
// extra lines and concatenation added for readability
deleteUser = function (e) {
var $this = $(this),
userId = $this.attr('data-id-user'),
href = $this.attr('href'),
deleteUrl = '/delete_user.php';
alert(userId);
alert(href);
// your actual clientside code to delete might look like this assuming
// the serverside logic for a delete is in /delete_user.php
$.post(deleteUrl, {username: userId}, function(){
alert('User deleted successfully!');
});
},
showOptions = function (e) {
$(this).closest('tr.options_panel').show();
},
userTmpl = '<div id="__USERNAME__" class="user_container">'
+ '<table>'
+ '<tr>'
+ '<td style="width:290px;font-size:15px;">__USERNAME__</td>'
+ '<td style="width:290px;font-size:15px;">__EMAIL__</td>'
+ '<td style="width:250px;font-size:15px;">__ACTIVE__</td>'
+ '<td>Options</td>'
+ '</tr>'
+ '<tr class="options_panel" style="display:none">'
+ '<td>Delete</td>'
+ '</tr>'
+ <'/table>'
+ '</div>';
$.ajaxSetup({
cache: false
})
$(document).delegate('#user_manage #user_container user_options', 'click.userlookup', showOptions)
.delegate('#user_manage #user_container user_delete', 'click.userlookup', deleteUser);
$.ajax({
url: 'http://example.com/test/www/user_lookup.php',
data: "",
dataType: 'json',
success: function (data) {
$.mobile.hidePageLoadingMsg();
var markup;
$member_friends.empty();
for (var i = 0, len = data.length; i < len; i++) {
markup = userTmpl.replace('__USERNAME__', data[i].username)
.replace('__ACTIVE__', data[i].active)
.replace('__EMAIL__', data[i].email);
$member_friends.append(markup);
}
}
});
});
Here's a really simple change you could make:
Replace this part:
onclick='showId();'>Delete</a>
With this:
onclick='showId("+data[i].id+");'>Delete</a>
And here's the new showId function:
function showId(id) {
alert(id);
}

Categories

Resources