Related to Modal Popup in jquery? - javascript

I am using modal popup in my project and its working perfectly, I used it in two buttons Edit and Delete, but the problem is when I edit I want to maintain its height according to the project but in case of delete I have to maintain in some other case, so what should I need to do so that I can use one modal but with different functionality.
here, is my modal popup code
<div class="modal inmodal" id="dynamicModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content animated flipInY">
<div class="modal-header">
<div id="">
<button type="button" class="close" data-dismiss="modal" id="closeModal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
</div>
</div>
<div class="modal-body" id="jq-server-response">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary modal-primary-btn jq-modal-primary-btn pull-right margin-left-5">Save changes</button>
<button type="button" class="btn btn-white modal-close-btn pull-right" data-dismiss="modal">Close</button>
<div class="pull-right jq-modal-form-loader hide">
<div class="sk-spinner sk-spinner-wave">
<div class="sk-rect1"></div>
<div class="sk-rect2"></div>
<div class="sk-rect3"></div>
<div class="sk-rect4"></div>
<div class="sk-rect5"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="dynamic-modal-spinner hide">
<div class="sk-spinner sk-spinner-wave">
<div class="sk-rect1"></div>
<div class="sk-rect2"></div>
<div class="sk-rect3"></div>
<div class="sk-rect4"></div>
<div class="sk-rect5"></div>
</div>
</div>
and I give height to modal - body like this
.modal-dialog {
overflow-y: initial !important
}
.modal-body {
height: 600px;
overflow-y: auto;
}
At the time of Edit it open in the way I want like
But, in case of delete, I want less height
here is my javascript code ...
$(function () {
$('.searchclick').click(function () {
$('.jq-billing-meter').removeClass('search-meter');
$(this).parents('.form-group').find('.jq-billing-meter').addClass('search-meter')
//$('.searchclick').parentsUntil('.formgroup');
//$(this).children('input').addClass('activetext');
})
$('body').delegate('.open-dynamic-modal-link', 'click', function (ev) {
var $this = $(this);
modal($this);
});
//click event on modal primary btn
$('body').delegate('.jq-modal-primary-btn', 'click', function (ev) {
var $this = $(this);
var $form = $(this).parents('.modal').find('form');
$form.submit();
});
});
function modal($this) {
var $spinner = $('.dynamic-modal-spinner');
// $("h2").siblings("p").css({ "color": "red", "border": "2px solid red" });
var dataUrl = $this.data('url');
var dataClose = $this.data('close');
var dataPrimary = $this.data('primary');
var dataTitle = $this.data('title');
var onLoadCallback = $this.data('onload');
var hasDataUrl = dataUrl != undefined && typeof dataUrl != "undefined" && dataUrl != '';
var url = hasDataUrl ? dataUrl : $this.attr('href');
if (hasDataUrl == false) {
ev.preventDefault();
}
var isLargeModal = $this.data('large');
var isMiniModal = $this.data('mini');
if (isLargeModal) {
$('#dynamicModal .modal-dialog').addClass('modal-lg');
} else {
$('#dynamicModal .modal-dialog').removeClass('modal-lg');
}
if (isMiniModal) {
$('#dynamicModal .modal-dialog').addClass('modal-sm');
$('#dynamicModal .modal-title').addClass('modal-small-title');
} else {
$('#dynamicModal .modal-dialog').removeClass('modal-sm');
$('#dynamicModal .modal-title').removeClass('modal-small-title');
}
// $('#dynamicModal .modal-title').text(title);
$('#dynamicModal .modal-title').html(dataTitle);
$('#dynamicModal .modal-body').html($spinner.html());
if (dataPrimary) {
$('#dynamicModal .modal-primary-btn').text(dataPrimary)
} else {
$('#dynamicModal .modal-primary-btn').addClass('hide')
}
if (dataClose) {
$('#dynamicModal .modal-close-btn').text(dataClose)
} else {
$('#dynamicModal .modal-close-btn').addClass('hide')
}
$('#dynamicModal').modal({ backdrop: 'static', keyboard: false },'show');
$('#dynamicModal .modal-body').load(url, function () {
// Now that the DOM is updated let's refresh the unobtrusive validation rules on the form:
$('#dynamicModal form').removeData('validator')
.removeData('unobtrusiveValidation');
jQuery.validator.unobtrusive.parse('#dynamicModal form');
//crystalPower.initDatePicker();
if (typeof window[onLoadCallback] == "function") { //if onLoadCallback is a valid function
window[onLoadCallback](); //call function
//} else if (typeof crystalPower[onLoadCallback] == "function") { //if onLoadCallback is a valid function
// crystalPower[onLoadCallback](); //call function
}
//if page has autoCompleteInit function available
if (typeof window["autoCompleteInit"] == "function") {
window["autoCompleteInit"]();
}
});
}

Related

Render this modal in ASP.NET MVC

I have a button that calls a modal that opens a Barcode Scanner. I would like to know if there is a way to add this code below that is a HTML file view and point to this view when click the button? I have tried to do it like this but it doesn't work for me.
What I did in the button I added the reference of the folder where is located with the data target but it does not call the modal it only works if I add on the same view .
File
<script src="https://cdnjs.cloudflare.com/ajax/libs/html5-qrcode/2.1.6/html5-qrcode.min.js"></script>
<div class="modal" id="livestream_scanner" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Barcode Scanner</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div id="qr-reader" style="width:450px"></div>
</div><!-- /.modal-body -->
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
<script>
function docReady(fn) {
// see if DOM is already available
if (document.readyState === "complete"
|| document.readyState === "interactive") {
// call on next available tick
setTimeout(fn, 1);
} else {
document.addEventListener("DOMContentLoaded", fn);
}
}
docReady(function () {
var resultContainer = document.getElementById('qr-reader-results');
var lastResult, countResults = 0;
function onScanSuccess(decodedText, decodedResult) {
if (decodedText !== lastResult) {
++countResults;
lastResult = decodedText;
window.location.href = "#Url.Action("Run", "Search")?criteria=" + lastResult;
}
}
var html5QrcodeScanner = new Html5QrcodeScanner(
"qr-reader", { fps: 10, qrbox: 250 });
html5QrcodeScanner.render(onScanSuccess);
});
</script>
<style>
##media screen and (max-width: 660px) {
#qr-reader {
max-width: 300px; /* New width for default modal */
}
}
</style>
</div><!-- /.modal -->
Button when the modal is being called
<li class="nav-item">
<a class="btn btn-outline-info mx-2 mx-sm-1" data-toggle="modal" data-target="#livestream_scanner" href="~/Orders/BarcodeScanner" title="Scan Barcode"><i class="bi bi-upc-scan"></i></a>
</li>

Why don't the Bootstrap Modal "close" and "x" buttons work?

I included a Bootstrap modal window in the HTML code of my webpage and I display it when a particular event occurs (a text field isn't empty and the string doesn't match any of the values in a JSON array).
The modal is displayed correctly when the event occurs. But the close button doesn't work, neither does the "X" button.
Shouldn't the buttons of a Bootstrap modal window work by default or should I add some other function to let them do the task?
This is the HTML code where I inserted the modal:
<div class="modal" tabindex="-1" role="dialog" id="myModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Error</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div id="testoMyModal" class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
And the following are the JAVASCRIPT snippets where the modal is called:
1)
function validateCitta() {
let text = $('#inlineFormInputCitta').val();
if (text === "") {
$("#errorLog").show();
}
else {
$.ajax({
url: "https://nominatim.openstreetmap.org/search?q=" + encodeURIComponent($("#inlineFormInputCitta").val()) + "&format=geocodejson",
dataType: "json",
success: function (data) {
var check = false;
for (let i = 0; i < data.features.length; i++) {
let typeCity = data.features[i].properties.geocoding.type;
if (typeCity === "city") {
let nameCity = data.features[i].properties.geocoding.name;
for (let i = 0; i < json.tappe.length; i++) {
let tappa = json.tappe[i];
let city = json.tappe[i].city;
if (city === nameCity) {
console.log("JSON file has been activated");
check = true;
$("#tbody").append("<tr><td>" + tappa.name + "</td><td>" + tappa.state + "</td><td>" + tappa.region + "</td><td>" + tappa.city + "</td></tr>");
$("#tabella").show();
}
;
}
;
}
}
if (!check) {
$('#myModal').show();
}
}
})
}
};
2)
function hideTutto() {
$('#myModal').hide();
};
Is it normal that these Modal buttons don't work by default? If not, why don't they?
E D I T [ S O L V E D ]
The issue came from a syntax error:
I wrote $('#myModal').show(); instead than $('#myModal').modal('show');
source: Modals methods
Now the buttons work.
You can change your code as below to get the output. You actually have to change the $('#myModal').show() into $('#myModal').modal('toggle');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script>
let text = $('#inlineFormInputCitta').val();
if (text === "") {
$("#errorLog").show();
}
else {
$.ajax({
url: "https://nominatim.openstreetmap.org/search?q=" + encodeURIComponent($("#inlineFormInputCitta").val()) + "&format=geocodejson",
dataType: "json",
success: function (data) {
var check = false;
for (let i = 0; i < data.features.length; i++) {
let typeCity = data.features[i].properties.geocoding.type;
if (typeCity === "city") {
let nameCity = data.features[i].properties.geocoding.name;
for (let i = 0; i < json.tappe.length; i++) {
let tappa = json.tappe[i];
let city = json.tappe[i].city;
if (city === nameCity) {
console.log("JSON file has been activated");
check = true;
$("#tbody").append("<tr><td>" + tappa.name + "</td><td>" + tappa.state + "</td><td>" + tappa.region + "</td><td>" + tappa.city + "</td></tr>");
$("#tabella").show();
}
;
}
;
}
}
if (!check) {
$('#myModal').modal('toggle');
}
}
})
}
function hideTutto() {
$('#myModal').modal('toggle');
};
</script>
<div class="modal" tabindex="-1" role="dialog" id="myModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Error</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div id="testoMyModal" class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
you can also use $('#myModal').modal('hide'); and $('#myModal').modal('show'); to accomplish your task.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script>
let text = $('#inlineFormInputCitta').val();
if (text === "") {
$("#errorLog").show();
}
else {
$.ajax({
url: "https://nominatim.openstreetmap.org/search?q=" + encodeURIComponent($("#inlineFormInputCitta").val()) + "&format=geocodejson",
dataType: "json",
success: function (data) {
var check = false;
for (let i = 0; i < data.features.length; i++) {
let typeCity = data.features[i].properties.geocoding.type;
if (typeCity === "city") {
let nameCity = data.features[i].properties.geocoding.name;
for (let i = 0; i < json.tappe.length; i++) {
let tappa = json.tappe[i];
let city = json.tappe[i].city;
if (city === nameCity) {
console.log("JSON file has been activated");
check = true;
$("#tbody").append("<tr><td>" + tappa.name + "</td><td>" + tappa.state + "</td><td>" + tappa.region + "</td><td>" + tappa.city + "</td></tr>");
$("#tabella").show();
}
;
}
;
}
}
if (!check) {
$('#myModal').modal('show');
}
}
})
}
function hideTutto() {
$('#myModal').modal('hide');
};
</script>
<div class="modal" tabindex="-1" role="dialog" id="myModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Error</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div id="testoMyModal" class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
For new comers using data-bs-dismiss="modal" instead of data-dismiss="modal" makes close button work. thanks to https://stackoverflow.com/a/65799124/8722913

Bootstrap 3 modal: make it movable/draggable without jquery-ui

I'm tring to develop some things:
make a bootstrap modal draggable/movable on the window without jquery-ui
I use backbone.js but I think this is not so important. In a piece of code I define my bootstram modal:
<div id="detailsContainer">
<div class="modal fade" id="someId" 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"><span class="glyphicon glyphicon-cloud-upload" aria-hidden="true"></span> Some Title</h4>
</div>
<div class="modal-body" id="content">
<form class="form-horizontal" role="form" id="modalFormBody">
... some content
</form>
</div>
<div class="modal-footer">
<div class="pull-right" id="modalButtonBar">
<button type="button" class="btn btn-default control-button" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary control-button" id="addButton">Add</button>
</div>
</div>
</div>
</div>
Now when I try to use set the modal draggable with this code:
var $container = $("#detailsContainer");
$container.on('mousedown', 'div', function() {
$(this).addClass('draggable').parents().on('mousemove', function(e) {
$('.draggable').offset({
top: e.pageY - $('.draggable').outerHeight() / 2,
left: e.pageX - $('.draggable').outerWidth() / 2
}).on('mouseup', function() {
$(this).removeClass('draggable');
});
});
e.preventDefault();
}).on('mouseup', function() {
$('.draggable').removeClass('draggable');
});
the behaviour is strange:
when I pick up the modal the modal goes out of window. I tried to fix changing some values to top and left, but nothing has been good.
when I pick some under element of the modal-body (for example an Input text), then I can move arround in the modal the input text. But I don't want this! I only want that the whole modal can be draggable/movable.
The example above I have found it on stackoverflow (Sorry I don't find the link on it). I find also some example with jquery-ui. But I don't want to use it. Only Jquery.
I have also tried: Dialog draggable, and JQuery Draggable Demo. But without success.
The first one don't make my modal draggable, and the second one I din't understand how to use it with $container
Can someone help me?
Update
$('body').on('mousedown', '.modal-dialog', function() {
$(this).addClass('draggable').parents().on('mousemove', function(e) {
$('.draggable').offset({
top: e.pageY - $('.draggable').outerHeight() / 2,
left: e.pageX - $('.draggable').outerWidth() / 2
}).on('mouseup', function() {
$(this).removeClass('draggable');
});
});
e.preventDefault();
}).on('mouseup', function() {
$('.draggable').removeClass('draggable');
});
But when I want to drag... it changes the position of where I picked it up the modal. It goes on the corner. Not there where I picked it up? How can I correct this? It's wrong to put the ".modal-dialog" on the mousedown function? And If this is wrong, which element I have to put it there?
And an other point: the elements that I have in the modal body (example drop down) must not be draggable. How can I exclude them?
This answer is too late, but in case someone (like me) was searching for a solution to this. Finally, my solution was to use this code:
(function ($) {
$.fn.drags = function (opt) {
opt = $.extend({ handle: "", cursor: "move" }, opt);
var $el = null;
if (opt.handle === "") {
$el = this;
} else {
$el = this.find(opt.handle);
}
return $el.css('cursor', opt.cursor).on("mousedown", function (e) {
var $drag = null;
if (opt.handle === "") {
$drag = $(this).parents('.modal-dialog').addClass('draggable');
} else {
$drag = $(this).parents('.modal-dialog').addClass('active-handle').parent().addClass('draggable');
}
var z_idx = $drag.css('z-index'),
drg_h = $drag.outerHeight(),
drg_w = $drag.outerWidth(),
pos_y = $drag.offset().top + drg_h - e.pageY,
pos_x = $drag.offset().left + drg_w - e.pageX;
$drag.css('z-index', 1000).parents().on("mousemove", function (e) {
$('.draggable').offset({
top: e.pageY + pos_y - drg_h,
left: e.pageX + pos_x - drg_w
}).on("mouseup", function () {
$(this).removeClass('draggable').css('z-index', z_idx);
});
});
e.preventDefault(); // disable selection
}).on("mouseup", function () {
if (opt.handle === "") {
$(this).removeClass('draggable');
} else {
$(this).removeClass('active-handle').parent().removeClass('draggable');
}
});
}
})(jQuery);
Then, when the modal is shown:
$('#modal').on('shown.bs.modal', function () {
$(this).find('.card-header').drags();
});
$('#modal').modal({ show: true, backdrop: 'static', keyboard: false });
I am using a card inside the modal dialog with an HTML like this:
<div id="modal" class="modal fade">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content animated bounceInRight">
<div class="modal-body">
<div class="card">
<div class="card-header border-bottom-0">My super title</div>
<div class="card-body">
<form >...</form>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" id="btnAlmacenar"><i class="fa fa-save"></i> Almacenar</button>
<button type="button" class="btn btn-danger" data-dismiss="modal"><i class="fa fa-close"></i> Cancelar</button>
</div>
</div>
</div>
</div>
This is the whole snippet if you want to try it:
(function ($) {
$.fn.drags = function (opt) {
opt = $.extend({ handle: "", cursor: "move" }, opt);
var $el = null;
if (opt.handle === "") {
$el = this;
} else {
$el = this.find(opt.handle);
}
return $el.css('cursor', opt.cursor).on("mousedown", function (e) {
var $drag = null;
if (opt.handle === "") {
$drag = $(this).parents('.modal-dialog').addClass('draggable');
} else {
$drag = $(this).parents('.modal-dialog').addClass('active-handle').parent().addClass('draggable');
}
var z_idx = $drag.css('z-index'),
drg_h = $drag.outerHeight(),
drg_w = $drag.outerWidth(),
pos_y = $drag.offset().top + drg_h - e.pageY,
pos_x = $drag.offset().left + drg_w - e.pageX;
$drag.css('z-index', 1000).parents().on("mousemove", function (e) {
$('.draggable').offset({
top: e.pageY + pos_y - drg_h,
left: e.pageX + pos_x - drg_w
}).on("mouseup", function () {
$(this).removeClass('draggable').css('z-index', z_idx);
});
});
e.preventDefault(); // disable selection
}).on("mouseup", function () {
if (opt.handle === "") {
$(this).removeClass('draggable');
} else {
$(this).removeClass('active-handle').parent().removeClass('draggable');
}
});
}
})(jQuery);
$(document).ready(function () {
$('#modal').on('shown.bs.modal', function () {
$(this).find('.card-header').drags();
});
$('#modal').modal({ show: true, backdrop: 'static', keyboard: false });
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script>
<div id="modal" class="modal fade">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content animated bounceInRight">
<div class="modal-body">
<div class="card">
<div class="card-header border-bottom-0">My super title</div>
<div class="card-body">
<form></form>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" id="btnAlmacenar"><i class="fa fa-save"></i> Almacenar</button>
<button type="button" class="btn btn-danger" data-dismiss="modal"><i class="fa fa-close"></i> Cancelar</button>
</div>
</div>
</div>
</div>
try this code surely it'll helps you, below code is without jquery ui
check this updated fiddle check here
$(function() {
$('body').on('mousedown', '#myModal', function(ev) {
$(this).addClass('draggable').parents().on('mousemove', function(e) {
$('.draggable').offset({
top: e.pageY - $('.draggable').outerHeight() /8,
left: e.pageX - $('.draggable').outerWidth() /8
}).on('mouseup', function() {
$(this).removeClass('draggable');
});
});
ev.preventDefault();
}).on('mouseup', function() {
$('.draggable').removeClass('draggable');
});
});
body {padding:50px;}
div {
cursor:move;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<div class="modal fade" id="myModal" 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">Modal title</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="recipient-name" class="control-label">Recipient:</label>
<input type="text" class="form-control" id="recipient-name">
</div>
<div class="form-group">
<label for="message-text" class="control-label">Message:</label>
<textarea class="form-control" id="message-text"></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>

Bootstrap generic modal with callbacks

I've replace my JS Confirm function with a bootstrap modal, this modal is async so I also had to change my code and add callbacks.
What I'm trying to is:
Pseudo Code
if `simApp["con1"]` then show first modal with 2 buttons
if return is clicked -> close modal.
if continue is clicked -> open second modal
if return is clicked -> close modal
if submit is clicked -> submit form (not included in code)
else open second modal
if return is clicked -> close modal
if submit is clicked -> submit form (not included in code)
This is all very simple when you don't use callbacks, which I'm fairly new to.
So this is what I did, its NOT working, I guess it has something to do with the generic use of the modal. - JSFIDDLE
HTML
<div class="modal fade" id="generalModalTwoButtons" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header bg-primary">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"></h4>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<button type="button" id="btn-return" class="btn btn-primary" data-dismiss="modal"></button>
<button type="button" id="btn-submit" class="btn btn-primary" data-dismiss="modal"></button>
</div>
</div>
</div>
</div>
<button id="go">GO</button>
JS
simApp = {};
simApp["con1"] = true; //in this code I hard-coded the conditions to ture
simApp["arr"] = [1];
$("#go").click(function () {
if (simApp["con1"] && simApp["arr"].length < 5) {
var msg = '<p>msg1</p>';
updateGeneralTwoButtonsModal('#a94442', 'header1', msg, 'Return', 'Continue', function (result) {
if (result === true) {
confirmBeforeSubmit(submitFormApproved);
}
});
} else {
confirmBeforeSubmit(submitFormApproved)
}
});
function submitFormApproved(result) {
if (result === true) {
console.warn("submitted");
}
}
function confirmBeforeSubmit(callback) {
var msg = '<p>msg2</p>';
if (simApp["con1"]) msg = '<p>msg2-changed</p>';
updateGeneralTwoButtonsModal('#31708f', 'header2', msg, 'Return', 'Submit', callback);
}
function updateGeneralTwoButtonsModal(color, title, body, btnReturn, btnSubmit, callback) {
var confirm = $('#generalModalTwoButtons');
confirm.find('.modal-header').css('color', color);
confirm.find('.modal-title').text(title);
confirm.find('.modal-body').html(body);
confirm.modal('show');
confirm.find('#btn-return').html(btnReturn).off('click').click(function () {
confirm.modal('hide');
callback(false);
});
confirm.find('#btn-submit').html(btnSubmit).off('click').click(function () {
confirm.modal('hide');
callback(true);
});
}
Any idea what I did wrong?
P.S - for learning purposes I would like to avoid using promises on this solution.
Here you go, the main problem I found was the fact that you don't block the propagation of the click event which automatically closes the modals. I added the event handler stopPropagation in the event of the continue/submit button.
simApp = {};
simApp["con1"] = true;
simApp["arr"] = [1];
$("#go").click(function () {
if (simApp["con1"] && simApp["arr"].length < 5) {
var msg = '<p>msg1</p>';
updateGeneralTwoButtonsModal('#a94442', 'header1', msg, 'Return', 'Continue', function (result) {
if (result === true) {
confirmBeforeSubmit(submitFormApproved);
}
});
} else {
confirmBeforeSubmit(submitFormApproved)
}
});
function submitFormApproved(result) {
if (result === true) {
console.warn("submitted");
}
}
function confirmBeforeSubmit(callback) {
var msg = '<p>msg2</p>';
if (simApp["con1"]) msg = '<p>msg2-changed</p>';
updateGeneralTwoButtonsModal('#31708f', 'header2', msg, 'Return', 'Submit', callback);
}
function updateGeneralTwoButtonsModal(color, title, body, btnReturn, btnSubmit, callback) {
var confirm = $('#generalModalTwoButtons');
confirm.find('.modal-header').css('color', color);
confirm.find('.modal-title').text(title);
confirm.find('.modal-body').html(body);
confirm.modal('show')
confirm.find('#btn-return').html(btnReturn).off('click').click(function () {
confirm.modal('hide');
callback(false);
});
confirm.find('#btn-submit').html(btnSubmit).off('click').click(function (event) {
event.preventDefault();
event.stopPropagation();
if(btnSubmit != "Continue") {
confirm.modal('hide');
}
callback(true);
});
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<div class="modal fade" id="generalModalTwoButtons" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header bg-primary">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"></h4>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<button type="button" id="btn-return" class="btn btn-primary" data-dismiss="modal"></button>
<button type="button" id="btn-submit" class="btn btn-primary" data-dismiss="modal"></button>
</div>
</div>
</div>
</div>
<button id="go">GO</button>

Insert Data from Modal Bootstrap MVC 4 + JQuery (Post Method)

I have a modal form that save me on certain data information, work correctly, but I need to update a in my view with the response and doesn't work correctly and bring me a list without format and class css, like when an error occurs, the modal disappears and brings back a page without css with all the validates error, what I have wrong in my code or that I do to fix it?
My Partial View
#model ControlSystemData.Models.Tourist
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel-Update">Ingresar Turista</h4>
</div>
#using(#Html.BeginForm("Create","Tourist", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<div class="modal-body" style="text-align:center; padding:10px;">
#if (!string.IsNullOrWhiteSpace(ViewBag.Error))
{
<div class="alert alert-danger alert-dismissable" id="danger">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
#ViewBag.Error
</div>
}
<div class="panel-body">
<div class="form-group">
#Html.TextBoxFor(u => u.Name, new { #class = "form-control", #placeholder = "Nombre del Pasajero" })
#Html.ValidationMessageFor(u => u.Name)
</div>
#*More Data Here*#
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Guardar</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
</div>
</fieldset>
}
My Modal Bootstrap
<!--Modal Tourist-->
<div class="modal fade" id="Modal-Tourist" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<p class="body">
</p>
</div>
</div>
</div>
<!--End Modal Tourist-->
My Controller
[HttpPost]
public ActionResult Create(Tourist collection)
{
if (ModelState.IsValid)
{
db.Tourist.Add(collection);
db.SaveChanges();
return RedirectToAction("IndexByEventsTourist", "Tourist", new { id = collection.id });
}
Response.StatusCode = 400;
return PartialView("Create", collection);
}
My Script
<script type="text/javascript" src="~/Scripts/jquery-2.1.4.js"></script>
<script type="text/javascript">
function clearErrors() {
$('#msgErrorNewTourist').html('');
$('#alert').html('');
}
function writeError(control, msg) {
var err_msg = '<div class="alert-message error"><a class="close" href="#">×</a><p>' + msg + '</p></div>';
$('#' + control).html(err_msg);
}
$(document).ready(function () {
$('#Modal-Tourist form').on('submit', function () {
if ($(this).valid()) {
$.ajax({
url: '#Url.Action("Create","Tourist")',
data: $(this).serialize(),
success: function (result) {
$('#Modal-Tourist').modal('hide');
$("#eventsDetailsList").html(result);
},
error: function (err) {
writeError('body', 'Wrong Data');
}
});
}
return false;
});
function getRequest(url) {
jQuery.noConflict();
$.ajax({
url: url,
context: document.body,
success: function (data) {
$('.modal-content p.body').html(data);
$('#Modal-Tourist').modal('show');
$('#Name').focus();
},
error: function (err) {
writeError('msgErrorNewTourist', err.responseText);
}
});
}
$('a.newTourist').click(function () {
var id = $(this).attr("eventsid");
var url = '#Url.Content("~/Tourist/Create")/' + id;
getRequest(url);
return false;
});
});
</script>
I need that the modal stay in your position with your errors or rendering my correctly with the update.
Thanks
Images
RedirectToAction
public ActionResult IndexByEventsTourist(int id)
{
ViewBag.id = id;
var eventsById = db.Events.Where(u => u.id == id).FirstOrDefault();
ViewBag.Events = eventsById;
var touristByEvent = db.Tourist.Where(u => u.id == id).Include(u => u.Events).ToList();
ViewBag.TouristByEvent = touristByEvent;
return PartialView("IndexByEvents", touristByEvent);
}
Parent page (Render Div with the Partial Render or Update from Modal)
<div class="col-lg-8">
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-plus"></i> Add
</div>
<div class="panel-body">
<div class="row">
<div id="msgErrorNewTourist"></div>
<div class="col-lg-12" id="eventsDetailsList">
#{Html.RenderAction("IndexByEventsTourist", "Tourist", new { id = Model.id });}
</div>
</div>
</div>
</div>
</div>
</div>
After many tries, I changed the <script></script> (my script it was very obsolete) and I modified the <script> of this answer for my intent of load content dynamically and Validate the form before Post, Many Thanks to Sthepen Muecke for provide me a solution and clarify my issues... Thank you so much.
New Code Script for Load Content Dinamically and Validate Inputs in Modal Bootstrap 3
<script type="text/javascript" src="~/Scripts/jquery-2.1.4.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('a.newTourist').click(function () {
var url = '#Url.Action("Create", "Tourist", new { id = #Model.id })';
$(jQuery.noConflict);
$('#ModalContent').load(url, function (html) {
var form = $("#Modal-Tourist form");
$.validator.unobtrusive.parse(form);
$("#Modal-Tourist").modal('show');
form.submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#Modal-Tourist').modal('hide');
var content = '#Url.Action("IndexByEventsTourist", "Tourist", new { id = #Model.id })';
$('#eventsDetailsList').load(content);
}
});
return false;
});
});
});
});
</script>

Categories