Using bootstrap modal with Tabpanel to set active tab - javascript

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.

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>

Doubleclick block Bootstrap Modal Window

When I doubleclick quickly, two modal windows open simultaneously and close button is blocked. You can try live demo in http://1card.digital/prb/modalprb1.html
Link to Open Modal
<a class="btn btn-primary btn-block btn-lg" data-toggle="modal" href="#myModalAgrP" id="modallinkAgrP" data-title="ModalPrb1Mdl">Open Modal</a>
JQuery to Open Modal
<script type = "text/javascript" > $(document).ready(function () {
jQuery('#modallinkAgrP').click(function (e) {
$('#myModalAgrP').modal('hide');
$('.modal-container').load($('#modallinkAgrP').data('title'), function (result) {
$('#myModalAgrP').modal({
show: true
});
});
});
});
$(document).on("hidden.bs.modal", "#myModalAgrP", function () {
$('#myModalAgrP').remove();
});
</script>
Modal Code
<div class="modal fade" id="myModalAgrP">
<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'><a target="_blank" href="#"><span class="fa fa-question-circle"></span></a> Bootstrap Modal</h4>
</div>
<div class="modal-body">
<div class="callout callout-info">Prueba de Bootstrap Modal</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
</div>
</div>
</div>
</div>
Thank's a lot for your answer, this code solve my double click problem...
$('a').on('click', function(e){
var $link = $(e.target);
e.preventDefault();
if(!$link.data('lockedAt') || +new Date() - $link.data('lockedAt') > 900) {
console.log('clicked');
// doSomething();
}
$link.data('lockedAt', +new Date());
});
You can specify "static" for a backdrop which doesn't close the modal on click.
For example:
jQuery('#modallinkAgrP').click(function (e) {
$('.modal-container').load($('#modallinkAgrP').data('title'), function (result) {
$('#myModalAgrP').modal({
show: true,
backdrop: 'static'
});
});
});

How to get the id and name of an object on button click and display them in a modal in asp.net view

I have a strongly typed view in which I am looping over some objects from a database and dispaying them in a jumbobox with two buttons in it. When I click one of the buttons I have a modal popping up. I'd like to have somewhere in this modal the name and the id of the corresponding object, but I do not really know how to do this. I am a bit confused where to use c# and where javascript. I am a novice in this, obviously.
Can someone help?
This is the code I have so far. I don't have anything in relation to my question, except the code for the modal :
#model IEnumerable<eksp.Models.WorkRole>
#{
ViewBag.Title = "DisplayListOfRolesUser";
}
<div class="alert alert-warning alert-dismissable">You have exceeded the number of roles you can be focused on. You can 'de-focus' a role on this link.</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var dataJSON;
$(".alert").hide();
//make the script run cuntinuosuly
$.ajax({
type: "POST",
url: '#Url.Action("checkNumRoles", "WorkRoles")',
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
if (data == false) {
$(".alert").show();
$('.btn').addClass('disabled');
//$(".btn").prop('disabled', true);
}
}
function errorFunc() {
alert('error');
}
});
</script>
#foreach (var item in Model)
{
<div class="jumbotron">
<h1>#Html.DisplayFor(modelItem => item.RoleName)</h1>
<p class="lead">#Html.DisplayFor(modelItem => item.RoleDescription)</p>
<p> #Html.ActionLink("Focus on this one!", "addWorkRoleUser", new { id = item.WorkRoleId }, new { #class = "btn btn-primary btn-lg" })</p>
<p> <button type="button" class="btn btn-default btn-lg" data-toggle="modal" data-target="#myModal">Had role in the past</button> </p>
</div>
}
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">#Html.DisplayFor(modelItem => item.RoleName)//doesn't work</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Save</button>
</div>
</div>
</div>
</div>
I think your confusing the server side rendering of Razor and the client side rendering of the Modal. The modal cannot access your Model properties as these are rendered server side before providing the page to the user. This is why in your code <h4 class="modal-title">#Html.DisplayFor(modelItem => item.RoleName)//doesn't work</h4> this does not work.
What you want to do is capture the event client side in the browser. Bootstrap allows you to achieve this by allowing you to hook into events of the Modal. What you want to do is hook into the "show" event and in that event capture the data you want from your page and supply that to the Modal. In the "show" event, you have access to the relatedTarget - which is the button that called the modal.
I would go one step further and make things easier by adding what data you need to the button itself as data-xxxx attributes or to DOM elements that can be easily access via JQuery. I have created a sample for you based on what you have shown to give you an idea of how it can be achieved.
Bootply Sample
And if needed... How to specify data attributes in razor
First of all
you will need to remove the data-toggle="modal" and data-target="#myModal" from the button, as we will call it manually from JS and add a class to reference this button later, your final button will be this:
<button type="button" class="btn btn-default btn-lg modal-opener">Had role in the past</button>
Then
In your jumbotron loop, we need to catch the values you want to show later on your modal, we don't want to show it, so we go with hidden inputs:
<input type="hidden" name="ID_OF_MODEL" value="#item.WorkRoleId" />
<input type="hidden" name="NAME_OF_MODEL" value="#item.RoleName" />
For each information you want to show, you create an input referencing the current loop values.
Now you finally show the modal
Your document.ready function will have this new function:
$('.modal-opener').on('click', function(){
var parent = $(this).closest('.jumbotron');
var name = parent.find('input[name="NAME_OF_MODEL"]').val();
var id = parent.find('input[name="ID_OF_MODEL"]').val();
var titleLocation = $('#myModal').find('.modal-title');
titleLocation.text(name);
// for each information you'll have to do like above...
$('#myModal').modal('show');
});
It simply grab those values we placed in hidden inputs.
Your final code
#model IEnumerable<eksp.Models.WorkRole>
#{
ViewBag.Title = "DisplayListOfRolesUser";
}
<div class="alert alert-warning alert-dismissable">You have exceeded the number of roles you can be focused on. You can 'de-focus' a role on this link.</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var dataJSON;
$(".alert").hide();
//make the script run cuntinuosuly
$.ajax({
type: "POST",
url: '#Url.Action("checkNumRoles", "WorkRoles")',
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
if (data == false) {
$(".alert").show();
$('.btn').addClass('disabled');
//$(".btn").prop('disabled', true);
}
}
function errorFunc() {
alert('error');
}
$('.modal-opener').on('click', function(){
var parent = $(this).closest('.jumbotron');
var name = parent.find('input[name="NAME_OF_MODEL"]').val();
var id = parent.find('input[name="ID_OF_MODEL"]').val();
var titleLocation = $('#myModal').find('.modal-title');
titleLocation.text(name);
// for each information you'll have to do like above...
$('#myModal').modal('show');
});
});
</script>
#foreach (var item in Model)
{
<div class="jumbotron">
<input type="hidden" name="ID_OF_MODEL" value="#item.WorkRoleId" />
<input type="hidden" name="NAME_OF_MODEL" value="#item.RoleName" />
<h1>#Html.DisplayFor(modelItem => item.RoleName)</h1>
<p class="lead">#Html.DisplayFor(modelItem => item.RoleDescription)</p>
<p> #Html.ActionLink("Focus on this one!", "addWorkRoleUser", new { id = item.WorkRoleId }, new { #class = "btn btn-primary btn-lg" })</p>
<p> <button type="button" class="btn btn-default btn-lg" data-toggle="modal" data-target="#myModal">Had role in the past</button> </p>
</div>
}
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">#Html.DisplayFor(modelItem => item.RoleName)//doesn't work</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Save</button>
</div>
</div>
</div>

auto resizing textarea in a modal

I'm creating a ASP.NET Webpage using Bootstrap and jQuery.
I have recently implemented a modal to show a log. The modal is shown when clicking a link:
<a data-toggle="modal" data-target="#logData">Open</a>
<div class="modal fade" id="logData" tabindex="-1" role="dialog" aria-labelledby="logDataLabel">
<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">Log for #Html.DisplayFor(model => model.Alias)</h4>
</div>
<div class="modal-body">
<textarea class="form-control log" rows="5" placeholder="Log is empty.">#Html.DisplayFor(model => model.Log)</textarea>
</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>
The modal contains a textarea that doesn't autoresize.
I have found the following code:
$('textarea').each(function () {
this.setAttribute('style', 'height:' + (this.scrollHeight) + 'px;overflow-y:hidden;');
}).on('input', function () {
this.style.height = 'auto';
this.style.height = (this.scrollHeight) + 'px';
});
which should enable my textareas to autoresize and it works other places in my code, but not in this modal above. At least not when typing in the textarea, but upon opening the modal it does seem to autoresize.
Does anyone have an idea of why? And eventually on how to fix it?
Thanks!
You can use this code which will work if the textarea is not hidden (e.g in a modal that is not shown yet)
let setHeight = (input) => {
input.style.overflow = 'hidden';
input.style.height = 0;
input.style.height = `${ input.scrollHeight + 2 }px`;
};
$('textarea').on('input, keyup', function () {
setHeight(this);
})
for bootstrap modal, u can do something like this:
$('.modal').on('shown.bs.modal', function () {
$(this).find('textarea').each(function () {
setHeight(this);
});
})

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>

Categories