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>
Related
How to display a pop-up notification in admin side when a customer click an order?. Now its not getting the pop-up notification?.when inspect the values getting.
var audio = document.getElementById("myAudio");
function playAudio() {
audio.play();
}
function pauseAudio() {
audio.pause();
}
Ajax
<script>
setInterval(function () {
$.ajax({
url: '{{route('get-order-data')}}',
dataType: 'json',
success: function (response) {
let data = response.data;
if (data.new_order > 0) {
playAudio();
$('#popup-modal').appendTo("body").modal('show');
}
},
});
}, 1000);
Controller
public function order_data()
{
$new_order = DB::table('orders')->where(['checked' => 0])->count();
return response()->json([
'success' => 1,
'data' => ['new_order' => $new_order]
]);
}
pop up code
<div class="modal" id="popup-modal">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-body">
<div class="row">
<div class="col-12">
<center>
<h2 style="color: rgba(96,96,96,0.68)">
<i class="tio-shopping-cart-outlined"></i> You have new order, Check Please.
</h2>
<hr>
</center>
</div>
</div>
</div>
</div>
</div>
Ajax
<script>
$(document).ready(function(){
setInterval(function () {
$.ajax({
url: '{{route('get-order-data')}}',
type: 'GET',
dataType: 'json',
success: function (response) {
$.each(response.new_order, function (key, value) {
if (value.new_order > 0) {
playAudio();
$('#popup-modal').modal('show');
}
});
}
});
}, 1000);
});
</script>
Controller
public function order_data()
{
$data = DB::table('orders')->where('checked', 0)->get();
$count = $data->count();
$res['new_order'] = array([
'success' => 1,
'new_order' => $count
]);
return response()->json($res);
}
You are displaying the popup through modal window. You can trigger the modal window through javascript. I hope the below code will be useful for you. Try this code in jsFiddle with jQuery enabled. Append the javascript code inside the ajax code where you need to display the notification.
$('.btn').click(function () {
$("#myModal").modal('show');
})
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="myModal" class="modal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p>Modal body text goes here.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<button class="btn">
Submit
</button>
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>
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"]();
}
});
}
I'm using the jquery below to control what happens when a tab is clicked in a AjaxControlToolkit tabcontainer.
If a hidden text input (hdnFormSaved) has a value of "True", the clicked tab is set as active (this.get_owner().set_activeTab(this)), else a confirm dialog is created. The clicked tab is only then set as active if confirmed via the dialog.
$(function () {
Sys.Extended.UI.TabPanel.prototype._header_onclick =
function (e) {
this.raiseClick();
if ($("[id$=hdnFormSaved]").val() == "True") {
this.get_owner().set_activeTab(this);
} else {
if (confirm('Do you want to change tab?'))
this.get_owner().set_activeTab(this);
else
return false;
}
};
});
This solution works perfectly. However, I would like to replace the confirm dialog with a bootstrap modal.
<div class="modal" id="myModal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<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">Warning</h4>
</div>
<div class="modal-body">
<p>Do you want to change tab?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">OK</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
I've got as far as initialising a modal inside the else block rather than a confirm dialog. From here, I'm not sure how to proceed to set the clicked tab as active if the modal's OK button is clicked. Can/should I listen for the event within the same else block?
$(function () {
Sys.Extended.UI.TabPanel.prototype._header_onclick =
function (e) {
this.raiseClick();
if ($("[id$=hdnFormSaved]").val() == "True") {
this.get_owner().set_activeTab(this);
} else {
$('#myModal').modal();
}
};
});
Any advice is welcome. Thanks.
Solved as below:
$(function () {
Sys.Extended.UI.TabPanel.prototype._header_onclick =
function (e) {
this.raiseClick();
if ($("[id$=hdnFormSaved]").val() == "True") {
this.get_owner().set_activeTab(this);
} else {
obj = this;
$('#myModal').modal();
$("#btn_okay").on("click", $.proxy(function () {
this.get_owner().set_activeTab(this);
}, this));
}
};
});
I gave the modal OK button an id of #btn_okay and used jquery's proxy to pass the context to the on anonymous function.
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>