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

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.

Related

Javascript dynamic switch doubling Ajax calls

I am having a problem with a jQuery click function. When a user clicks a HTML button, my jQuery dynamically loads some styled checkbox's/toggle switches based upon their corresponding on/off state stored in a database.
I then added a click function to each dynamically loaded toggle switch so that when a user clicks it, it updates the database with the new state, it then, with Ajax, calls the GetAllSwitches function again loading the current state of the switches from the DB back into the resultScreen.
It works, updates the state in the DB correctly, but the program remembers previous 'clicks' and runs them all again followed by the new click state every time a user clicks. So on the first click it makes 1 http request, 2nd 2, 3rd 4, 4th 8 etc. The problem being after a few clicks the ajax calls become huge.
I'm not that experienced in Javascript so I am aware my code is verbose and I am clearly missing something, but are there any fixes or better approaches to this?
In summary what I want to achieve is:
User clicks allSwitches
Ajax call to a database which returns all objects with a toggle switch on screen
Have the toggle switch's clickable which updates the database with new state
Allow the switches to be clicked as many times as the user likes only making one update to the DB
HTML
<fieldset>
<legend> Get All Lights Dynamically</legend>
<input type="button" value="Show All" id="allSwitches"/>
</fieldset>
<fieldset>
<div id='resultScreen'></div>
</fieldset>
JavaScript
$(document).ready(function(){
$("#allSwitches").click(function(){
$.ajax({
url: 'GetAll',
type: 'GET',
dataType: 'text',
success: function(data) {
getAllSwitches(data)
});
});
});
function getAllSwitches(data){
var tr;
myData = $.parseJSON(data);
for(var i = 0; i < myData.length; i++){
tr = $('<tr/>');
if(myData[i].state=="On"){
tr.append('<div id="togs' + i + '">' + '<label class="switch">' +
'<input type="checkbox" class="' + myData[i].lightName +'" checked>' +
'<div class="slider round"></div>'
+'</label>' + '</div>');
tr.append("<td>" + myData[i].lightName +
" is " + myData[i].state + "</td>");
$('#resultScreen').append(tr);
var className = '.' + myData[i]lightName;
var lightName = myData[i].lightName;
var state = "Off";
upTog(className, lightName, state);
} else if (myData[i].state=="Off"){
tr.append('<label class="switch">' +
'<input type="checkbox" class="' + myData[i].lightName +'" >' +
'<div class="slider round"></div>'
+'</label>');
tr.append("<td>" + myData[i].lightName +
" is " + myData[i].state + "</td>");
$('#resultScreen').append(tr);
var className = '.' + myData[i].lightName;
var lightName = myData[i].lightName;
var state = "On";
upTog(className, lightName, state);
}
}
}
function upTog(className, lightName, state){
$(document).on('click', className, function() {
$.ajax({
url: 'UpdateLight?lightName=' + lightName + "&state=" + state,
type: 'POST',
dataType: 'text',
success:function(data){
$.ajax({
url: 'GetAll',
type: 'GET',
dataType: 'text',
success: function(data) {
$('#resultScreen').empty();
getAllSwitches(data);
}});
}
})
});
}
Many thanks.
The easiest way to do it is to unbind the previous click before set the new one.
Change upToge() body like this:
$(className).unbind( "click" );
$(className).on('click', function () {
/* Your ajax call here */
});
You're adding the click handler to the className, which is not changing when you empty the #resultsScreen div. You can see how the handlers pile up in this jsbin: http://jsbin.com/hizigutogi/edit?js,console,output (fill the div, click the red box, empty it, fill it again, and click it a few more times)
Try passing the reference to the jQuery object tr into upTog and adding the click handler onto it directly, instead of attaching it to the class name.

How to get the values from dynamically generated html textboxes in asp.net

I want to fetch the values from dynamically created html textboxes in my aspx page. Now first I want to check if the textbox exists or not. If exists then I want to fetch values from these texboxes. Here is the code which I am using for creating textboxes dynamically
<script type="text/javascript">
var counter = 2;
$(document).ready(function () {
$("#addButton").click(function () {
if (counter > 3) {
alert("Limit Exceeds");
return false;
}
var $wrap = $('#TextBoxesGroup');
var dynamichtml = '<div id="div' + counter + '"><div class="mcity"><label> Leaving from</label><input type="text" name="textbox' + counter + '" id="textbox' + counter + '" class="auto"/> </div><div class="mcity"> <label> Going to</label> <input type="text" name="textbox' + counter + '" id="textbox' + counter + 1 + '" class="auto"/> </div><div class="mcity"> <label> Going to</label> <input type="text" name="textbox' + counter + '" id="textbox' + counter + 11 + '" class="auto"/> </div>';
$wrap.append(dynamichtml);
counter++;
});
$("#removeButton").click(function () {
if (counter == 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxesGroup").find("#div"+ counter).remove();
// $("#TextBoxesGroup").find("#textbox" + counter+1).remove();
});
$(".auto").live("focus", function () {
$(this).autocomplete({
source: function (request, response) {
var textval = request.term; // $(this).val();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Home.aspx/GetAutoCompleteData",
data: "{'code':'" + textval + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
});
});
</script>
This code is generating textboxes generating and I am fetching data from my database using json autocomplete process.After this I am trying to send the information to another page using javascript the code that I write for this is below
<script type="text/javascript">
$(function () {
$("#btnPost").bind("click", function () {
//Create a Form
var $form = $("<form/>").attr("id", "data_form")
.attr("action", "Complete.aspx")
.attr("method", "post");
$("body").append($form);
//Append the values to be send
AddParameter($form, "txtleft", $("#txtSearchleft").val());
AddParameter($form, "txtright", $("#txtSearchright").val());
//Send the Form
$form[0].submit();
});
});
function AddParameter(form, name, value) {
var $input = $("<input />").attr("type", "hidden")
.attr("name", name)
.attr("value", value);
form.append($input);
}
</script>
This work fine for textboxes which placed default in my page. But for the textboxes that generate dynamically after these textboxes I dnt know how to send values of those textboxes to my next page
Javascript and asp.net experts please help me to resolve this
Thanks
You can get the controls values using FormCollection. Note that it works on name rather than Id.
You need to keep the count and follow some naming convention for name of your controls.
Create a asp.net hidden field and keep the control count in that. And get according the values of the hidden field.
Msdn link
well if you were to assign your form an id
you could just serialize your form and post it using ajax if you wanted
$.post("complete.aspx",$("#data_form").serialize(),function(response){
//react to the post here
});

Update Javascript object with code from AJAX request

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();
}
}

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