Why these confirmation modal is not showing up? - javascript

I use a template that uses bootstrap. I'm having trouble with showing a modal.
The form has a jquery validation, if everything is ok then when clicking on submit a confirmation modal should appear to ask user if he is sure he wants to store that information. If form doesn't pass validation then a simple message appears.
For the mentioned actions I build this:
<form action="#" id="form_sample_2" class="form-horizontal">
<div class="alert alert-error hide">
<button class="close" data-dismiss="alert"></button>Existen errores en el formulario. Por favor verifique.</div>
<!-- modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel3" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h3 id="myModalLabel3">Cargar Usuario</h3>
</div>
<div class="modal-body">
<p></p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Cerrar</button>
<button data-dismiss="modal" class="btn green" id="btnYes">Confirmar</button>
</div>
</div>
<!-- end modal -->
</form>
As you can see, modal and error message has the attribute "hide"...
the js file:
var handleValidation2 = function () {
// for more info visit the official plugin documentation:
// http://docs.jquery.com/Plugins/Validation
var form2 = $('#form_sample_2');
var error2 = $('.alert-error', form2);
var success2 = $('#myModal', form2);
//IMPORTANT: update CKEDITOR textarea with actual content before submit
form2.on('submit', function () {
for (var instanceName in CKEDITOR.instances) {
CKEDITOR.instances[instanceName].updateElement();
}
})
form2.validate({
errorElement: 'span', //default input error message container
errorClass: 'help-inline', // default input error message class
focusInvalid: false, // do not focus the last invalid input
ignore: "",
rules: {
//some code
},
submitHandler: function (form) {
success2.show();
error2.hide();
}
//some code
On this snippet, if form doesn't pass validation then error2.hide() function shows up the alert error message.
Problem comes when form passes validation when success2.show() function should show confirmation modal, but it's not doing that. Nothing appears when form is ok and I'm wondering what am I doing wrong.
Any help would be really much appreciated.
J.

Instead of success2.show(); use success2.modal('show')
This should fix your issue

submitHandler: function (form) {
success2.removeAttr('aria-hidden');
success2.show();
error2.hide();
}
do u try to remove att aria-hidded. hope that work for u

Related

Modal won't close and prevent default on no click, and won't execute func on yes click

I have a modal with two buttons. One is a yes button and one is a no button. If yes button is pressed, I would like the remainder of the function to execute. If no btn clicked, I would like the page to prevent default and not execute. However, it seems that regardless of which button is clicked, nothing happens besides the modal closing. I am using a modal example I found elsewhere, so this may be the issue. After glancing at it for some time I cannot seem to find where the issue is. Am I missing something small? Or perhaps my Jquery is wrong? Below is my code:
Modal:
<!-- Modal for delete-->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content border-primary mb-3 box-shadow-none img-responsive">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="card-body bg-light">
<div id="del" class="center">
<label>Are you sure you want to delete?</label>
</div>
</div>
<div class="modal-footer">
<div id="deleteYes">
<button type="button" class="btn btn-default" data-dismiss="modal" id="deleteYes">Yes</button>
</div>
<div id="deleteNo">
<button type="button" class="btn btn-default" data-dismiss="modal" id="deleteNo">No</button>
</div>
</div>
</div>
</div>
</div>
And here is my Jquery:
$(".btnDeleteTerminalCommand").click(function (e) {
$("#deleteModal").modal('toggle');
if ($("#deleteNo").click) {
return e.preventDefault();
}
var rowId = "#" + $(this).data("rowindex");
var row = $(rowId);
var termId = row.find(".tdTermId").html().trim();
var cmdId = row.find(".tdCmdId").html().trim();
var cmdVal = row.find(".tdCmdVal").html().trim();
var cmdID = row.find(".cmdID").html().trim();
var data = {
TerminalID: termId,
CommandID: cmdId,
CommandValue: cmdVal,
ID: cmdID
};
$.ajax({
url: '#Url.Action("DeleteTerminalCommand", "TerminalCommand")',
type: "POST",
data: data,
success: function (response) {
console.log("Success");
window.location.href = response.Url;
}
});
});
Any advice helps! Thank you!
Your click handler will toggle the modal and immediately continue to execute the rest of the function before the user can click anything. If your modal has two buttons, create a click handler for each button. Perhaps the No button just closes the modal. The Yes button handler can execute the actions required to accomplish the task.
$(".btnDeleteTerminalCommand").click(function(e){
$("#deleteModal").modal('toggle');
}
$("#deleteNo").click(function(e){
$("#deleteModal").modal('hide');
}
$("#deleteYes").click(function(e){
// build data object
// ajax post
}

Bootstrap modal not closing second time from JS code

I have following code in a Partial View in an MVC project:
$(document).ready(function () {
$("##Html.IdFor(m => m.AanwezigheidChauffeurID)").change(function () {
setModalBody("busy", "Even geduld, de gegevens worden opgehaald...");
$("#modalDialog").modal({ keyboard: false, backdrop: "static" });
var chauffeurRequest = $.ajax({
url: '#Url.Action("GetAanwezigheid", "Invoer")',
data: { id: $("##Html.IdFor(m => m.AanwezigheidChauffeurID)").val() },
async: true,
cache: false,
type: "POST"
});
chauffeurRequest.done(function (data, textStatus, jqXHR) {
$("#entriesDiv").empty();
$("#entriesDiv").append(data);
$(".hoursInput:first").trigger("change");
$("#modalDialog").modal("hide");
});
chauffeurRequest.fail(function (request, textStatus, errorThrown) {
setModalBody("error");
});
});
});
This is the markup of the modal:
<div class="modal fade" id="modalDialog" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalDialogLabel">Xwift</h5>
<button type="button" class="close closeModalButton" data-dismiss="modal" aria-label="Sluiten">
<span aria-hidden="true">×</span>
</button>
</div>
<div id="modal-dialog-body" class="modal-body">
</div>
<div class="modal-footer">
<button type="button" id="closeModalButton" disabled class="btn btn-primary closeModalButton" data-dismiss="modal">Sluiten</button>
</div>
</div>
</div>
</div>
The situation:
$("##Html.IdFor(m => m.AanwezigheidChauffeurID)") is referring to a select element. When I change the value of the drop-down, the AJAX request is launched and the modal dialog is shown. When the request is done, the modal is closed by calling $("#modalDialog").modal("hide");.
Now when I change the value of the drop-down again, the request is launched again and the modal is shown again. When the request is done, I can see the changes in the DOM through the backdrop from the modal, but the modal won't close anymore. When I call the line $("#modalDialog").modal("hide"); in the console to test it, the modal does close.
Is there some reason why it won't close the second, third or more time?
Too bad I already asked this question before finding following question here on StackOverflow: Bootstrap 4 Modal Not Closing Properly On Hide
Several comments and answers refer to the fact that the fade class disrupts the whole hiding of the modal. I have tried removing this class and it worked for me as well. Sadly, I didn't find a reason for this.

How clear the previous data while open the bootstrap modal?

Main page contains the google map(div), after selecting state from map, i will try to open bootstrap modal and load the selected county map inside the bootstrap.
Firsttime click Texas state(javascript ShowModalDialog() called) then bootstrap modal alert shows Texas then close.
Second time Ohio is selected, now first alert showing Texas then Ohio.
Why the previous state is showing here?
<script type="text/javascript">
function ShowModalDialog(stateid) {
$('#myModal').modal('show').on('shown.bs.modal', function () {
alert(stateid);
$("#myModal #myModalLabel").html(document.getElementById("statename").value);
var datajson = GetCountyData(stateid);
});
}
</script>
<!-- Modal -->
<div class="modal fade modal-wide" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" style="color: #808080">
<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">Modal title</h4>
</div>
<div class="modal-body">
....
....
..
.
</div>
</div>
</div>
</div>
I think this is bug in bootstrap, because i have several ways to clear modal
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
});
But stil got no 'perfect' solutin, becasue with every new call, modal on screen goes a little down, than in firebug i saw there is a lots of modal there just hidden, than i found
http://bootboxjs.com/
And all my problem were solved
$("#myModal").on("hide", function() { // remove the event listeners when the dialog is dismissed
$("#myModal a.btn").off("click");
});
$("#myModal").on("hidden", function() { // remove the actual elements from the DOM when fully hidden
$("#myModal").remove();
});
$("#myModal").modal({ // wire up the actual modal functionality and show the dialog
"backdrop" : "static",
"keyboard" : true,
"show" : true // ensure the modal is shown immediately
});

ASP.NET MVC validation not working on bootstrap modal

I can't get the bootstrap modal and asp.net mvc validation start working together. I've got a complex form with some validation displayed in bootstrap modal. Unfortunetely when I hit the submit button the validation doesn't work at all.
The form uses standard asp.net mvc validation. Below there is a part of it just to get the idea of how it is build:
#using (Html.BuildForm().AddClass("form-horizontal").Id("contact-add-popup").EncType(FormEncType.MultipartData).Begin()) {
#Html.AntiForgeryToken()
#Html.Partial("_Alerts")
<div class="control-group">
<div class="control-group company-field">
#Html.BuildLabelFor(m => m.Name).AddClass("control-label")
<div class="controls">
#Html.BuildTextBoxFor(m => m.Name).AddClass("input-xxlarge")
#Html.ValidationMessageFor(m => m.Name)
</div>
</div>
(...)
Here is my modal:
<div id="createContactModal" class="modal hide fade modal-contact" tabindex="-1" role="dialog" aria-labelledby="createContactModalLabel" aria-hidden="true" data-backdrop="static">
<div class="modal-header">
<h4 class="modal-label" id="createContactModalLabel">Add contact</h4>
</div>
<div class="modal-body">
#Html.Partial("_CreateContact", new ContactCreateModel())
</div>
<div class="modal-footer">
Zapisz
<button class="btn" data-dismiss="modal" aria-hidden="true">Zamknij</button>
</div>
And some javascript that I hope to get the validation working:
$('#createContactModal').on('shown', function () {
$("#contact-add-popup").removeData("validator");
$("#contact-add-popup").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("#contact-add-popup");
});
$('#contact-add-popup').on('submit', function(e){
e.preventDefault();
$.validator.unobtrusive.parse($("#contact-add-popup"));
if ($('#contact-add-popup').valid()){
alert('AJAX');
}
});
The line if ($('#contact-add-popup').valid()) returns always true. How can I get the modal and validation to work?
You should try this way:
var form = $("#contact-add-popup")
.removeData("validator")
.removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(form);
Stackoverflow: unobtrusive validation not working with dynamic content
After some research I found that javascript validation script files were missing - so the client side validation was not working at all. After including these files everything works fine.
Thanks for all answers.
Add this in the base view, load modal and enable client side validation.
#section scripts {
#{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
#* The normal bootstrap behavior is to only grab the content
for the modal once, if you need to pull in different partial
views then the data on the modal will have to be cleared. *#
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
<script type="text/javascript">
$(function () {
$('#modal-container').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget); // Button that triggered the modal
var url = button.attr("href");
var modal = $(this);
//enable client side validation after page is loaded
modal.find('.modal-content').load(url, function () {
$('#registration_form').removeData("validator");
$('#registration_form').removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse('#registration_form');
});
});
});
</script>
}

$.post keeps redirecting me

I have problem with jquery $.post function. I use this function a lot and same function works fine except in one case and I don't understand why it keeps redirecting me after script was executed, here is js code:
var record;
$('.delbtt').on('click', function(e){
e.preventDefault();
var deleteid = $(this).parent().parent().find('#id').text();
record = $(this).parent().parent();
$('#delrecord').empty().val(deleteid);
});
$(document).on('submit', '#delteform', function() {
var formData = $(this).serialize();
$.post('includes/delete.php',formData,processData);
function processData(data){
record.remove();
};
});
HTML:
<!-- Modal -->
<div class="modal fade" id="deleteFormModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form id="deleteform" class="form-horizontal" role="form" action="includes/delete.php" method="POST"> <!-- -->
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Delete record</h4>
</div>
<div class="modal-body">
<p>Are you sure you want to delete this person?</p>
</div>
<input type="hidden" id="delrecord" name="delrecord" value="" />
<div class="modal-footer">
<button type="button" class="btn btn-default empty" data-dismiss="modal">Cancel</button>
<button id="delentry" type="submit" class="btn btn-danger">Delete Person</button>
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
I know that function is executed successfully, because if I put alert("Why is this not working?"); after record.remove();, I can see alert and in background code executed, but instead of staying at the same page it redirects me to 'includes/delete.php'. I tried disabling all other $.post functions that I have in my JS, I tried using $('#deleteform').submit(), I tried putting it outside of my main $(document).ready(function() {}); same results... Always same result it redirects me after function completes instead of staying on a page. Does anybody have idea why am I getting this behavior?
php code:
<?php
include('budgetprop/Initialize.php');
Database::GetInstance()->ConnectToServer($errors);
$record = $_POST['delrecord'];
# CONNECT TO DB
if(Database::GetInstance()->ConnectToServer($errors)){
$insertSQL1 = "DELETE FROM salaries WHERE record_id = '".$record."' ";
$stmt1 = sqlsrv_query(Database::GetInstance()->databaseConnection, $insertSQL1);
# IF THERE IS AN ERROR
if(!$stmt1){
echo "Error, cannot delete record";
}else{
Database::GetInstance()->LastInsertId($stmt1);
}
# IF ALL QUERIES WERE SUCCSESSFUL, COMMIT THE TRANSACTION, OTHERWISE ROLLBACK
if($stmt1 && !$errors){
sqlsrv_commit(Database::GetInstance()->databaseConnection);
# FREE THE STATEMENT
Database::GetInstance()->FreeDBStatement($stmt1);
echo "success";
return true;
}else{
sqlsrv_rollback(Database::GetInstance()->databaseConnection);
# FREE THE STATEMENT
Database::GetInstance()->FreeDBStatement($stmt1);
return false;
}
# NO CONNECTION WAS MADE
}else{
return false;
};
?>
preventDefault() doesn't work either
It sounds like your form is still being submitted, hence the redirect. You can stop it with preventDefault()...
$(document).on('submit', '#deleteform', function(e) {
e.preventDefault();
var formData = $(this).serialize();
$.post('includes/delete.php',formData,processData);
function processData(data){
record.remove();
};
});
Assuming "deleteform" is the ID of a form element on your page, within which you have an input or button of type "submit", I would suggest changing the delentry button to have a type of "button".
Most browsers will perform a POST/GET on a form that has an input or button of type submit when that button is clicked.
I would then update your jQuery event handler to select the button and specify an onclick event:
$('#delentry').click(function() {
...
});
If you wish to maintain some form of graceful degradation, you could leave the markup as a submit type button and on $(document).ready(), update the type of the button to be "button".

Categories