i am trying to initiate a popup/modal screen - javascript

I am developing a chat screen and i want to initiate a modal when an option on the screen is selected, i am unable t do it. kindly help me.
here is my html code where you can insert the option code.
<section id="demo">
<div class="vertical-align">
<div class="container">
<div class="row">
<div class="col-sm-6 col-sm-offset-3 col-xs-offset-0">
<div class="card no-border">
<div id="chat" class="conv-form-wrapper">
<form action="" method="GET" class="hidden">
<select data-conv-question="Here is my features! Enjoy.">
<option value="google" data-callback="googleMap">Google Map</option>
<option value="bing" data-callback="dawaai">Medicine Comparison`</option>
</select>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
The function called when data-call-back is:
function google(stateWrapper, ready) {
window.open("https://www.google.com/maps/place/Agha+Khan+Hospital+Pond+No.1/#24.8935763,67.0690012,17z/data=!3m1!4b1!4m5!3m4!1s0x3eb33edd90fa1943:0xd423034e388220fa!8m2!3d24.8935997!4d67.0713131");
ready();
}
function bing(stateWrapper, ready) {
window.open("https://dawaai.pk/");
ready();
}
The code for jquery is here:
<script type="text/javascript" src="jquery-1.12.3.min.js"></script>
<script type="text/javascript" src="dist/autosize.min.js"></script>
<script type="text/javascript" src="dist/jquery.convform.js"></script>
as i am unable to insert the complete file for jquery i am inserting the link form where you can have the complete code for chatbot.
https://github.com/eduardotkoller/convForm

You can try this:
View:
<div id="DemoModal" class="modal fade" role="dialog" data-keyboard="false" data-backdrop="static">
<div class="modal-dialog">
<div class="modal-content" id="modal-content">
</div>
</div>
</div>
Jquery:
function OpenModel(Title, Body, modalsize) {
$("#DemoModal").find(".modal-content").html(Body).after(function (e) {
if (modalsize == null) {
modalsize = 'modal-lg'
}
$("#DemoModal").find(".modal-dialog").attr('class', 'modal-dialog ' + modalsize + '');
$("#DemoModal").find(" ").html(Title);
$("#DemoModal").modal("show");
})
}
And when you need to call pop up then simply pass:
OpenModel("", data, '')
in jquery.

Related

Call JavaScript Function Contained on _Layout.cshtml

Please help, new web developer alert!
MVC + JavaScript :)
I have a .cshtml page that has a submit button. When I press that button I want to call a JavaScript function contained on my _Layout.cshtml page.
Unfortunately I get a function not found error.
'ReferenceError: validateCheckBoxesInForm is not defined'
Here is the cshtml page...
#model FrontEnd.Web.Areas.PresentationToPolicy.ViewModels.CaseSummary.InsurersReferralViewModel
#{
ViewBag.Title = "Refer To Insurers";
}
<div>
<form asp-area="PresentationToPolicy" asp-controller="CaseSummary" asp-action="ReferToInsurers" method="POST" id="documentDownload">
<div class="panel panel-danger">
<div class="panel-body" style="padding-bottom: 15px">
<div class="row">
<div class="col-md-12">
<input class="btn btn-success btn-lg" type="submit" value="Finish" onclick="validateCheckBoxesInForm(event, 'documentDownload', 'Whooops!', 'You Must Select At Least One Insurer For Referal')" style="max-width: 100%; width: 100%"/>
</div>
</div>
</div>
</div>
</form>
</div>
Here a cut down version of my _Layout.cshtml (the script is loaded just after bootstrap etc, at the start of the body)
#inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body style="background-color: #f6f8fa">
<environment include="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/jquery-ui/jquery-ui.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/js/dist/manifest.js"></script>
<script src="~/js/dist/vendor.js"></script>
<script src="~/js/dist/scripts.js" asp-append-version="true"></script>
</environment>
<div class="container body-content">
#RenderBody()
<hr style="margin-bottom: 2px; padding-bottom: 2px" />
<footer>
<p style="vertical-align: baseline">© 2017 - ABACUS Portfolio Portal</p>
</footer>
</div>
#RenderSection("Scripts", required: false)
</body>
</html>
Oh and the script that contains the function!
function validateCheckBoxesInForm(event, formId, title, message) {
let validated = false;
let form = $(`#${formId}`);
let elements = form.elements;
event.preventDefault();
for (var i = 0; i < elements.length; i++) {
if (elements[i].type === 'checkbox') {
if (elements[i].checked) {
validated = true;
form.submit();
break;
}
}
}
if (validated === false) {
$('<div></div>')
.appendTo('body')
.html(
`<div id="validateModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content" style="border-color: #f00">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">
${title}
</h3>
</div>
<div class="modal-body">
<h4>${message}</h4>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal" style="width: 150px">Ok</button>
</div>
</div>
</div>
</div>`
);
$('#validateModal').modal('show');
}
}
And finally a cut down version of 'View Source'
<body style="background-color: #f6f8fa">
<script src="/lib/jquery/dist/jquery.js"></script>
<script src="/lib/jquery-ui/jquery-ui.js"></script>
<script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="/js/dist/manifest.js"></script>
<script src="/js/dist/vendor.js"></script>
<script src="/js/dist/scripts.js?v=iHOVZCmLJ7F7ev0DnwzRmkZgp-zu74ZoPGBIra9EaIk"></script>
<div class="container body-content">
<form method="POST" id="documentDownload" action="/PresentationToPolicy/CaseSummary/ReferToInsurers/43cffe87-2d8f-43eb-8ad2-e0b046fc8d20">
<div class="panel panel-danger">
<div class="panel-body" style="padding-bottom: 15px">
<div class="row">
<div class="col-md-12">
<input class="btn btn-success btn-lg" type="submit" value="Finish" onclick="validateCheckBoxesInForm(event, 'documentDownload', 'Whooops!', 'You Must Select At Least One Insurer For Referal')" style="max-width: 100%; width: 100%"/>
</div>
</div>
</div>
</div>
</form>
</body>
</html>
If I press view source and click on the script link I get this...
webpackJsonp([19],{
/***/ 749:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(750);
/***/ }),
/***/ 750:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
//Global Functions that will be run of every page
//Called via _Layout.cshtml
function validateCheckBoxesInForm(event, formId, title, message) {
var validated = false;
var form = $('#' + formId);
var elements = form.elements;
event.preventDefault();
for (var i = 0; i < elements.length; i++) {
if (elements[i].type === 'checkbox') {
if (elements[i].checked) {
validated = true;
form.submit();
break;
}
}
}
if (validated === false) {
$('<div></div>').appendTo('body').html('<div id="validateModal" class="modal fade">\n <div class="modal-dialog">\n <div class="modal-content" style="border-color: #f00">\n <div class="modal-header">\n <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>\n <h3 class="modal-title">\n ' + title + '\n </h3>\n </div>\n <div class="modal-body">\n <h4>' + message + '</h4>\n </div>\n <div class="modal-footer">\n <button type="button" class="btn btn-danger" data-dismiss="modal" style="width: 150px">Ok</button>\n </div>\n </div>\n </div>\n </div>');
$('#validateModal').modal('show');
}
}....
So I guess my question is how to I call the function contained on the _Layout page from the child cshtml page?
I guess I could use a script section on the page, but this function is shared by multiple places. So I kinda need a central location to keep the code dry.

Problems displaying dataTable in modal in html partial view

I asked a question here yesterday about this issue but got downvoted, probably because I didn't include any code which is understandable.
Hopefully this question will be more complete and allow you to help me more easily.
So I have 3 views in play:
StudentsList
Script
#{
ViewBag.Title = "StudentsList";
Layout = "~/Views/Shared/_LayoutM.cshtml";
}
#Scripts.Render("~/Scripts/charts")
#Styles.Render("~/Content/formsaltcss")
#model Mvc.Models.StudentViewModel
<script type="text/javascript">
$(document).ready(function () {
$('#AddStudentData').click(function () {
var type = 'student';
var id = 0;
$('#holderArea').html('');
if (!$('#studentDropDown option:selected').length) {
ToastrWarning('Please select a student before running the report');
return;
}
id = $('#studentDropDown').val();
var data = { id: id };
$.ajax({
url: '/Student/StudentAnalysisFiltered',
async: false,
data: data,
dataType: 'html',
success: function (data) {
$('#holderArea').html(data);
}
});
});
});
Relevant HTML
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="margin-bottom0 text-center">Student Analysis</h3></div>
<div class="panel-body">
<div class="row">
<div class="col-sm-12">
<form class="form-horizontal">
<div class="form-group">
<div class="row">
<label class="col-sm-2 control-label">Student Name</label>
<div class="col-sm-4">
#Html.DropDownListFor(c => c.Students, new SelectList(Model.Students, "StudentID", "Name"), "Choose Student"
, new { id = "studentDropDown", #class = "form-control input-sm", data_width = "100%" })
</div>
<div class="col-sm-offset-2 col-sm-10">
<button id="AddStudentData" type="button" class="btn btn-sm btn-primary">Select</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<div id="holderArea">
</div>
StudentAnalysisSelected
Script
#using Data
#using Mvc.Helpers
#model Mvc.Models.StudentViewModel
#Scripts.Render("~/Scripts/datatables")
<script>
function StudentScoresModal(studentID, answer, result) {
$('#scoresTable').hide();
$('#scoresSpinner').show();
$('#scoresModal').modal('show');
var testID = #Html.Raw(Model.testID );
$.ajax({
cache: false,
url: "/Student/StudentScoresDrillthrough",
data: { 'studentID': studentID, 'answer': answer, 'result': result, 'testID': testID},
success: function (data) {
$('#scoresTable').html(data);
$('#scoresTable').show();
$('#scoresSpinner').hide();
},
error: function () {
toastr.options.positionClass = 'toast-bottom-right';
toastr.options.backgroundpositionClass = 'toast-bottom-right';
toastr.options.timeOut = 3000;
toastr.error('Unable to get student results.');
}
});
}
</script>
Relevant HTML
<div id="holderArea">
<button type="button" class="btn btn-sm btn-primary" onclick="StudentScoresModal(id, '', '')" id="#q.StudentID">View Scores</button>
</div>
<div class="modal in modal-stack" id="scoresModal" aria-hidden="false">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"><strong>Student Scores</strong></h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-xs-12">
<div class="table-responsive" id="scoresTable" style="display:none">
</div>
<div class="sk-cube-grid absolute-center top-85" id="scoresSpinner" style="display:none">
<div class="sk-cube sk-cube1"></div>
<div class="sk-cube sk-cube2"></div>
<div class="sk-cube sk-cube3"></div>
<div class="sk-cube sk-cube4"></div>
<div class="sk-cube sk-cube5"></div>
<div class="sk-cube sk-cube6"></div>
<div class="sk-cube sk-cube7"></div>
<div class="sk-cube sk-cube8"></div>
<div class="sk-cube sk-cube9"></div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-sm btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
StudentScoresPartial
Script
<script>
$(document).ready(function () {
$('#studentScores').dataTable({
"data": #Html.Raw(Model.StudentScoresJson),
"columns":[
{ "sName": "StudentID" },
{ "sName": "Answer" },
{ "sName": "Result" }
]
});
});
</script>
HTML
<table id="studentScores" class="display table table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>StudentID</th>
<th>Answer</th>
<th>Result</th>
</tr>
</thead>
<tfoot>
<tr>
<th>User</th>
<th>Answer</th>
<th>Response</th>
</tr>
</tfoot>
<tbody></tbody>
</table>
How it all works
On the 'StudentsList' view there is a dropdown with list of students, and a 'Select' button to filter on an individual. OnClick this clears the holderArea div and passes studentID to the controller method, which returns a partial view 'StudentAnalysisSelected' and places it inside the holderArea div.
Now a graph is loaded with details specific to the indivudual. When clicked the 'scoresTable' is hidden and the modal is shown and an ajax call is made to StudentScoresDrillthrough controller, which returns the 'StudentScores' partial that is placed into the html of 'scoresTable'.
The problem
Now this all works perfectly first time I filter by student. I click 'Select', the graph loads, I click the graph and the datatable displays neatly in the modal.
However for reasons unknown to me when I click 'Select' again to re-filter, and click on the graph that is loaded all I see is the modal appear with the loading spinner, and it stops there. No errors pertaining to datatables in the console, or anything out of the ordinary for that matter.
I appreciate this is a bit of a read, but i'd be keen to hear any thoughts on what could be causing my issue.
Thanks!
It's because your dom is reloaded and so you loose your event attached.
If you attach ypur event like so, this should do, see doc :
$('#AddStudentData').on('click',function () {});
First try calling dataTable after filter button click using $('#studentScores').dataTable();
If this doesn't work
Instead on your refilter click write:
$('#studentScores').dataTable();
After your partialview is fully loaded. And bind your list in table directly e.g :
StudentID
Answer
Result
#foreeach(var item in Model)
{
item.User
item.Answer
item.Response
}
Finally tracked it down and it was because the modal show was called before the table show.
Thanks to those who posted suggestions, it's much appreciated

Page keeps loading when inserting reference to jquery

I really feel this is a stupid question but I could not figure out:
Here my cshtml file, and it's rendered just fine:
#model CrashTestScheduler.Entity.Model.Channel
#{
string editFormat = string.Format("<button type='button' class='editForm' data-val-id=\"{0}\"><span class='ico-edit'></span></button>", ".Id");
const string DeleteFormat = "<button type='button' class='awe-btn' onclick=\"awe.open('deleteChannel', { params:{ id: .Id } })\"><span class='ico-del'></span></button>";
const string EditFormat = "<button type='button' class='awe-btn' onclick=\"awe.open('editChannel', { params:{ id: .Id } })\"><span class='ico-edit'></span></button>";
}
<script>
$(function() {
awe.popup = bootstrapPopup;
});
var getChannelGroupNameHandler = function (item) {
if (item.ChannelGroupName == null || item.ChannelGroupName=='') {
item.ChannelGroupName = $("#ChannelGroupId option:selected").text();
}
}
</script>
<div id="wrap">
<div id="page-heading">
<ol class="breadcrumb">
<li>Home</li>
<li class="active">Channels</li>
<li style="display:none;"></li>
</ol>
</div>
<div class="container">
<div class="col-md-12" id="gridRowChannels">
<div class="col-md-12">
<div class="panel panel-midnightblue-header">
<div class="panel-heading">
<h3>Channel List</h3>
<div class="options">
</div>
</div>
<div class="panel-body">
<div class="row-sub">
<button type="button" id="btnAddProject" class="btn btn-primary" onclick="awe.open('createChannel')">
Add Channel
</button>
</div>
<div class="row-sub">
#Html.Awe().InitPopupForm().Name("createChannel").Url(Url.Action("Create", "ChannelsGrid")).Success("itemCreated('ChannelsGrid',getChannelGroupNameHandler)").OkText("Add").Title("Add Channel")
</div>
<div class="row-sub">
#Html.Awe().InitPopupForm().Name("deleteChannel").Url(Url.Action("Delete", "ChannelsGrid")).Success("itemDeleted('ChannelsGrid')").Parameter("gridId", "ChannelsGrid").Height(200).Modal(true).Title("Delete Channel").OkText("Delete")
</div>
<div class="row-sub">
#Html.Awe().InitPopupForm().Name("editChannel").Group("Channel").Url(Url.Action("Edit", "ChannelsGrid")).Success("itemUpdated('ChannelsGrid',getChannelGroupNameHandler)").OkText("Save").Title("Edit Channel")
</div>
<div class="row-sub">
#(Html.Awe().Grid("ChannelsGrid")
.Url(Url.Action("GetItems", "ChannelsGrid"))
.Columns(
new Column {Name = "Name", Header = "Channel Name", Sort = Sort.Asc},
new Column {Name = "ChannelGroup.Name", Header = "Channel Group", ClientFormat = ".ChannelGroupName"},
new Column {ClientFormat = DeleteFormat, Width = 50},
new Column {ClientFormat = EditFormat, Width = 50}
)
.Sortable(true)
.SingleColumnSort(true)
.LoadOnParentChange(false)
.PageSize(20)
.Groupable(false))
</div>
</div>
</div>
</div>
</div>
<div class="col-md-12" id="pnlEditproject" style="display: none;">
</div>
</div>
</div>
But I want to use jquery to use jquery validation later on. So here I inserted them to the file.
<script src="~/Scripts/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.validate.min.js"></script>
Now the file could not be rendered and the page keeps loading and loading. Any clues?
Looks like you already have access to jQuery library in this page since you are using...
$(function() {
awe.popup = bootstrapPopup;
});
Please remove the new references and try to view page source to find out the list of libraries that are already available.

How to load image into Bootstrap Modal from JSON Flickr API

Below is the code I am working with as an example.
When I click each image from the Flickr feed I want to be able to load the Bootstrap Modal (which it does) but display that particular photo in the Modal (which it currently doesnt).
I've tried numerous different things. But I am unable to get it to work.
Example at http://jahax.com/ins/
<div class="container">
<h2 style="text-align: center;">Demonstration</h2>
<p class="text-center">Demo of Bootstrap, jQuery & JSON API</p>
<div class="row text-center">
</div>
<div id="images" class="row text-center"> </div>
</div>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="nyModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Demo of Modal</h4>
</div>
<div class="modal-body">
<img id="mimg" src="">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
// Start jQuery Function
$(document).ready(function(){
// JSON API to access Flickr
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=winter&format=json&jsoncallback=?", displayImages);
function displayImages(data) {
var iCount = 0;
var htmlString = "<div class=row>";
$.each(data.items, function(i,item){
if (iCount < 18) {
var sourceSquare = (item.media.m).replace("_m.jpg", "_q.jpg");
htmlString += '<a class="btn" data-toggle="modal" data-target="#myModal">';
htmlString += '<img src="' + sourceSquare + '">';
htmlString += '</a>';
}
iCount++;
});
// HTML into #images DIV
$('#images').html(htmlString + "</div>");
// Close down the JSON function call
}
// End jQuery function
});
</script>
<script type="text/javascript">
// Send Content to Bootstrap Modal
$('img').on('click',function()
{
var sr=$(this).attr('src');
$('#mimg').attr('src',sr);
$('#myModal').modal('show');
});
</script>
Change your 2nd script to this:
<script type="text/javascript">
// Send Content to Bootstrap Modal
$(document).on('click', 'img', function(){
var sr=$(this).attr('src');
$('#mimg').attr('src',sr);
$('#myModal').modal('show');
});
</script>

Bootstrap modal not firing following partial ajax load

I'm using Bootstrap with the latest version of jQuery and am having an issue displaying a modal following a partial update of the page via Ajax.
The modal fires ok multiple times before the UpdateRegister function runs after 60 seconds, after that I receive a "0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'modal'" when I click on the button to open the modal again.
The button that fires the modal ('#cmdAdd') is outside the Div updated by the Ajax call.
The javascript is as below:
$(function() {
// Display Add Visitor modal
$("#cmdAdd").on("click", function () {
var url = "/Visitor/Add/";
$.get(url, function (data) {
$("#myModal").html(data);
$('#myModal').modal('show');
});
});
// Update register every 60 seconds
setInterval(function () {
UpdateRegister();
}, 60000);
});
function UpdateRegister() {
var currentDate = new Date();
var day = currentDate.getDate();
var month = currentDate.getMonth() + 1;
var year = currentDate.getFullYear();
var thisDate = month + "/" + day + "/" + year;
var url = "/Visitor/RegisterList?date=" + thisDate + "&filter=current";
$.get(url, function (data) {
$("#RegisterList").html(data);
});
}
HTML is as follows:
<div class="row">
<div class="col-lg-12">
<h2>#Model.Date.DayOfWeek #Model.Date.ToLongDateString()</h2><br />
<div class="btn-group pull-right">
<button type="button" class="btn btn-danger" id="cmdEmergency">Emergency</button>
<button type="button" class="btn btn-default" id="cmdAdd">Add Visitor</button>
<button type="button" class="btn btn-default" id="cmdAddBulk">Add Bulk Visitors</button>
</div>
<ul class="nav nav-tabs">
<li class="active">Current Register <span class="label label-success" id="CountIn">#Model.VisitorsIn</span></li>
<li>Visitors Expected <span class="label label-success">#Model.VisitorsExpected</span></li>
<li>All Visitors <span class="label label-success" id="CountTotal">#Model.TotalVisitors</span></li>
</ul>
<div class="tab-content">
<!-- Visitors currently in the building -->
<div class="tab-pane active" id="register">
<br /><br />
<div class="row">
<div class="col-lg-12">
<div id="RegisterList">
#Html.Action("RegisterList", new { date = Model.Date, filter="current" })
</div>
</div>
</div>
</div>
<!-- Expected visitors not yet arrived -->
<div class="tab-pane" id="expected">
<br /><br />
<div class="row">
<div class="col-lg-12">
<div id="ExpectedList">
#Html.Action("RegisterList", new { date = Model.Date, filter="expected" })
</div>
</div>
</div>
</div>
<!-- All visitors for the day -->
<div class="tab-pane" id="all">
<br /><br />
<div class="row">
<div class="col-lg-12">
<div id="AllList">
#Html.Action("RegisterList", new { date = Model.Date, filter="all" })
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="myModal">
<!-- Modal content goes here -->
</div><!-- /.modal -->
How can I ensure that the modal still works after the update?
I know it sounds trivial but are you possibly missing a reference to bootstrap.js within the AJAX Html? Adding a reference worked for me when I faced the same error.
I think your #myModal just disappear when #RegisterList is set the data. You should go to check about it.

Categories