I tried to display modal after the submission J query Step form. But some time modal immediately disappear and sometimes does not appear.
The Following code works fine on online simulator on SO and modal appear perfectly. But modal does not appear on my browser.
$(document).ready(function() {
function adjustIframeHeight() {
var $body = $('body'),
$iframe = $body.data('iframe.fv');
if ($iframe) {
// Adjust the height of iframe
$iframe.height($body.height());
}
}
// IMPORTANT: You must call .steps() before calling .formValidation()
$('#student_questions')
.steps({
headerTag: 'h2',
bodyTag: 'section',
autoFocus: true,
enableContentCache: true,
transitionEffect: 'fade',
transitionEffectSpeed: 170,
onStepChanged: function(e, currentIndex, priorIndex) {
// You don't need to care about it
// It is for the specific demo
adjustIframeHeight();
},
// Triggered when clicking the Previous/Next buttons
onStepChanging: function(e, currentIndex, newIndex) {
var fv = $('#student_questions').data('formValidation'), // FormValidation instance
// The current step container
$container = $('#student_questions').find('section[data-step="' + currentIndex +'"]');
// Validate the container
fv.validateContainer($container);
var isValidStep = fv.isValidContainer($container);
if (isValidStep === false || isValidStep === null) {
// Do not jump to the next step
return false;
}
return true;
},
// Triggered when clicking the Finish button
onFinishing: function(e, currentIndex) {
var fv = $('#student_questions').data('formValidation'),
$container = $('#student_questions').find('section[data-step="' + currentIndex +'"]');
// Validate the last step container
fv.validateContainer($container);
var isValidStep = fv.isValidContainer($container);
if (isValidStep === false || isValidStep === null) {
return false;
}
return true;
},
onFinished: function(e, currentIndex) {
// Uncomment the following line to submit the form using the defaultSubmit() method
$('#student_questions').formValidation('defaultSubmit');
// For testing purpose
$('#welcomeModal').modal();
}
})
.formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
// This option will not ignore invisible fields which belong to inactive panels
exclude: ':disabled',
fields: {
subject_name: {
validators: {
notEmpty: {
message: 'Please Provide Subject Name'
}
}
},
chapter_name: {
validators: {
notEmpty: {
message: 'Please Provide Chapter Name'
}
}
},
qtype_name: {
validators: {
notEmpty: {
message: 'Please Provide Question Type Name'
}
}
}
}
});
});
.wizard .content {
min-height: 100px !important;
width: 74%;
}
.wizard .content > .body {
width: 100% !important; !important; !important; !important;
height: auto !important; !important; !important;
padding: 15px !important; !important;
position: relative !important;
}
.wizard > .actions {
width: 74%;
}
<html>
<head>
<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.2/js/bootstrap.min.js"></script>
<script src="http://formvalidation.io/vendor/formvalidation/js/formValidation.min.js"></script>
<script src="http://formvalidation.io/vendor/formvalidation/js/framework/bootstrap.min.js"></script>
<script src="http://formvalidation.io/vendor/jquery.steps/js/jquery.steps.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
<link href="http://formvalidation.io/vendor/jquery.steps/css/jquery.steps.css" rel="stylesheet"/>
<link href="http://formvalidation.io/vendor/formvalidation/css/formValidation.min.css" rel="stylesheet"/>
</head>
<body>
<div class="container">
<div class="row">
<h1>Now you are in Study section</h1>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-10">
<!--Form-->
<form id="student_questions" method="post" class="form-horizontal">
<h2>Choose Subject</h2>
<section data-step="0">
<div class="form-group">
<div class="col-md-2"></div>
<label class="col-md-3 control-label">Subject Name: </label>
<div class="col-md-3">
<select class="form-control" name="subject_name" id="subject_name">
<option value="">Select Subject</option>
<option value="e">English</option>
</select>
</div>
</div>
</section>
<h2>Choose Chapter</h2>
<section data-step="1">
<div class="form-group">
<div class="col-md-2"></div>
<label class="col-md-3 control-label">Select Chapter: </label>
<div class="col-md-3">
<select class="form-control" name="chapter_name" id="chapter_name">
<option value="">Select Chapter</option>
<option value="e">English</option>
</select>
</div>
</div>
</section>
<h2>Choose type of questions</h2>
<section data-step="2">
<div class="form-group">
<div class="col-md-2"></div>
<label class="col-md-3 control-label">Select Type of Question</label>
<div class="col-md-3">
<select class="form-control" name="qtype_name" id="qtype_name">
<option value="">Select Questions Types</option>
<option value="e">English</option>
</select>
</div>
</div>
</section>
</form>
<!--End Form-->
</div>
</div>
</div>
<div class="modal fade" id="welcomeModal">
<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">Modal title</h4>
</div>
<div class="modal-body">
<p>Completed...</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">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</body>
</html>
Related
I am receiving a bunch of ERR_HTTP2_PROTOCOL_ERROR messages in dev tools after 1 of the pages submits a form to a controller and then the controller displays a different view.
This is the sequence of events:
OnlineEnrollmentController presents Index.cshtml.
The View Index.cshtml displays text to the user and the user clicks a button to submit a form.
The form is sent to OnlineEnrollmentController/Agreement where a View is returned.
The View Agreement.cshtml is presented to the user and the user clicks a button to submit a form.
The form is sent to OnlineEnrollmentController/Profile where the ActionResult Profile reads data from a database, populates a model and returns the model to the View Profile.cshtml.
The View Profile.cshtml is presented to the user and the user clicks a button to submit a form.
The form is sent to OnlineEnrollmentController/Rate where the ActionResult Rate reads data from a database, populates a model and returns the model to the View Rate.cshtml.
The View Rate.cshtml is presented to the user and asks the user to enter a rate into a text box. The user enters a rate and clicks on the button to submit the form.
The form is sent to OnlineEnrollmentController/Election where the ActionResult Election gets the rate that was populated and stores in a TempData field. A new list of object is created where each object contains 3 fields and is returned to the View Election.cshtml.
The View Election.cshtml uses a foreach loop to display the contents of the list of object.
All this logic works except now I am receiving this ERR_HTTP2_PROTOCOL_ERROR when the View Election.cshtml is loaded.
Here are the specifics:
The application has a shared view called _NoMenu.cshtml. This is the contents of the file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<title>#ViewData["Title"]</title>
<link rel="stylesheet" href="~/css/site.css" />
<script src="https://use.fontawesome.com/54ec0da54f.js"></script>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous" />
<!-- font awesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous" />
<style>
/* Style for showing in progress bar
--------------------------------------------------*/
.submit-progress {
position: fixed;
top: 30%;
left: 50%;
height: 6em;
padding-top: 2.3em;
/* The following rules are the
ones most likely to change */
width: 20em;
/* Set 'margin-left' to a negative number
that is 1/2 of 'width' */
margin-left: -10em;
padding-left: 2.1em;
background-color: #17a2b8a8;
color: black;
-webkit-border-radius: 0.4em;
-moz-border-radius: 0.4em;
border-radius: 0.4em;
box-shadow: 0.4em 0.4em rgba(0,0,0,0.6);
-webkit-box-shadow: 0.4em 0.4em rgba(0,0,0,0.6);
-moz-box-shadow: 0.4em 0.4em rgba(0,0,0,0.6);
}
.hidden {
visibility: hidden;
}
.submit-progress i {
margin-right: 0.5em;
}
.mb-5, .my-5 {
margin-bottom: 1.5rem !important;
}
.scrollHeight {
height: 85vh;
}
.hideit {
display: none;
}
.width95 {
width: 95%;
}
.myDIV {
height: 75%;
overflow: auto;
}
.content500 {
height: 500px;
}
.content600 {
height: 600px;
}
.content800 {
height: 800px;
}
</style>
</head>
<body>
<div>
#RenderBody()
</div>
</body>
</html>
I use this for any page in my application where I dont want to show a standard bootstrap menu structure.
Here is the contents of the view Rate.schtml:
#model AccuRecordV3.Models.OnlineEnrollment_Indicative_Verify
#{
ViewData["Title"] = "Online Enrollment - Rate";
Layout = "~/Views/Shared/_NoMenu.cshtml";
}
#using (Html.BeginForm("Election", "OnlineEnrollment", FormMethod.Post))
{
<section id="rate" class="vh-100" style="background-color: #508bfc;">
<div class="container py-5 h-100">
<div class="row d-flex justify-content-center align-items-center h-100">
<div class="col-12 col-md-8 col-lg-6 col-xl-5">
<div class="card shadow-2-strong" style="border-radius: 1rem;">
<div class="card-body p-5 text-center scrollHeight">
<h3 class="mb-5">Online Enrollment</h3>
<h5 class="mb-5">Step 1 of 3</h5>
<div id="rateDIV" class="myDIV">
<div id="ratecontent" class="content500">
<div class="form-outline mb-4">
<label class="form-label text-left width95">
#Model.messageLiteral
</label>
</div>
<div class="form-outline mb-4">
<label class="form-label text-left width95">
The minimum contribution rate allowed by your plan is #Model.outputMinPct and the
maximum contribution rate allowed by your plan is #Model.outputMaxPct
</label>
</div>
<div class="form-outline mb-4">
<label class="form-label text-left">
How much would you like to contribute?
</label>
</div>
<div class="form-outline mb-4">
<input type="number" id="electedRate" asp-for="electedRate" class="form-control form-control-lg rate" value="#Model.electedRate" placeholder="0" min="#Model.ss_CtrbKMinPct" step="1" max="#Model.ss_CtrbKMaxPct" />
<label class="form-label text-danger" for="electedRate" id="rateerrorLabel"> </label>
</div>
<button class="btn btn-primary btn-lg btn-block" type="button" id="rateButton" disabled onclick="return DisplayProgressMessage(this, 'rate');">Next</button>
<button class="btn btn-outline-primary btn-lg btn-block" type="button" id="cancelRateButton" onclick="return Cancel(this, 'rate');">Cancel</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
}
<script>
$(function () {
var rate = 0;
$('.rate').each(function () {
rate += parseInt($(this).val());
});
var minRate = parseInt("#Model.ss_CtrbKMinPct");
var maxRate = parseInt("#Model.ss_CtrbKMaxPct");
if (rate < minRate || rate > maxRate) {
$("#rateButton").prop("disabled", true);
} else {
$("#rateButton").prop("disabled", false);
}
$('.rate').change(function () {
var rate = 0;
$('.rate').each(function () {
rate += parseInt($(this).val());
});
var minRate = parseInt("#Model.ss_CtrbKMinPct");
var maxRate = parseInt("#Model.ss_CtrbKMaxPct");
if (rate < minRate || rate > maxRate) {
$("#rateButton").prop("disabled", true);
} else {
$("#rateButton").prop("disabled", false);
}
})
})
function DisplayProgressMessage(ctl, msg) {
$(ctl).prop("disabled", true).text(msg);
$("#submitButton").prop("disabled", true);
$(".submit-progress").removeClass("hidden");
const myTimeout = setTimeout(function () {
$("form").submit();
}, 5);
}
</script>
The view Rate.schtml works correctly, using jquery to validate the rate the user enters and then submits the form back to the controller.
This is the contents of Election.cshtml:
#model AccuRecordV3.Models.OnlineEnrollment_Indicative_Verify
#{
ViewData["Title"] = "Online Enrollment - Rate";
Layout = "~/Views/Shared/_NoMenu.cshtml";
}
#using (Html.BeginForm("Summary", "OnlineEnrollment", FormMethod.Post))
{
<section id="elections" class="vh-100" style="background-color: #508bfc;">
<div class="container py-5 h-100">
<div class="row d-flex justify-content-center align-items-center h-100">
<div class="col-12 col-md-8 col-lg-6 col-xl-5">
<div class="card shadow-2-strong" style="border-radius: 1rem;">
<div class="card-body p-3 text-center scrollHeight">
<h3 class="mb-5">Online Enrollment</h3>
<h5 class="mb-5">Step 2 of 3</h5>
<div id="electionsDIV" class="myDIV">
<div id="electionscontent" class="content600">
<div class="form-outline mb-4">
<label class="form-label text-left width95">
These are the funds that are available to you. You can allocate your contribution to any/all of these funds. Remember, you wont be able to submit your elections all your total elections added together equal 100%.
</label>
</div>
#foreach (var localRecord in Model.electionData)
{
<div class="row width95">
<label for="NewPct" class="col-sm-9 col-form-label text-left">#localRecord.FundName</label>
<div class="col-sm-3">
<input type="number" class="form-control election" id="NewPct" name="NewPct" min="#localRecord.MinPct" max="#localRecord.MaxPct" value="0">
<input type="number" id="HostFID" name="HostFID" hidden value="#localRecord.HostFID" />
</div>
</div>
}
<div class="row width95">
<label class="col-sm-9 col-form-label text-left">Total</label>
<label id="ElectionTotal" name="ElectionTotal" class="col-sm-3 col-form-label text-right">0%</label>
</div>
<button class="btn btn-primary btn-lg btn-block" type="button" id="electionButton" disabled onclick="return DisplayProgressMessage(this, 'elections');">Next</button>
<button class="btn btn-outline-primary btn-lg btn-block" type="button" id="cancelElectionButton" onclick="return Cancel(this, 'elections');">Cancel</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
}
<script>
$(function () {
$('.election').change(function () {
var sum = 0;
$('.election').each(function () {
sum += parseInt($(this).val());
});
var totalElection = sum + "%";
$("#ElectionTotal").text(totalElection)
if (sum == 100) {
$("#electionButton").prop("disabled", false);
} else {
$("#electionButton").prop("disabled", true);
}
})
})
function DisplayProgressMessage(ctl, msg) {
$(ctl).prop("disabled", true).text(msg);
$("#submitButton").prop("disabled", true);
$(".submit-progress").removeClass("hidden");
const myTimeout = setTimeout(function () {
$("form").submit();
}, 5);
}
</script>
When this view loads, and I look at dev tools, this is what I see:
and
So, for some reason, this error is preventing jquery.min.js from loading which in turn causes the '$' not defined error.
It looks like this error is also preventing the style sheet from loading properly as well.
Some research into this says it's a CORS issue but I dont see how I could have a CORS issue on one page (Elections.schtml) and not on the others (Index.schtml, Agreement.schtml, Profile.schtml, and Rate.schtml).
Any idea how to resolve this?
Thanks.
I have this bootstrap layout, which is a container inside an accordion-item. There is a dropdown button, containing messages and there's another button that opens a modal to insert a new message and display it in the dropdown list, using localStorage.
When the page loads or is refreshed, I can select the dropdown item normally, but when I add the item, it actually shows up in the list, but I can't select it nor any other item and the selected item is kept there, until the page is reloaded again.
I can still add more messages using the modal and they will still show up in the list.
There's no error in the console to guide me.
The JavaScript code is located at the bottom of the code.
Demonstrating video: https://www.youtube.com/watch?hd=1&v=fhNfpOaJbGs
HTML:
<div class="container">
<div class="row justify-content-center">
<div class="col-4">
<div class="dropdown">
<button class="btn btn-secondary" type="button" id="ddMensagens" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Selecione Mensagem
</button>
<div class="dropdown-menu scrollable-menu" id="mensagem" aria-labelledby="ddMensagens">
</div>
</div>
</div>
<div class="col-4">
<button type="button" class="btn btn-outline-success btn-sm" data-bs-toggle="modal" data-bs-target="#staticBackdrop" title="Clique para cadastrar uma nova mensagem">
Cadastrar Nova Mensagem
</button>
<div class="modal fade" id="staticBackdrop" data-bs-backdrop="false" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered"">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalMensagem">Nova Mensagem</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fechar"></button>
</div>
<div class="modal-body">
<div class="container">
<div class="row">
<div class="col">
<div class="form-group">
<label for="txtMensagem">Digite sua mensagem</label>
<input type="text" class="form-control" id="txtMensagem" placeholder="Mensagem" style="width: 400px">
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-bs-dismiss="modal">Fechar</button>
<button type="button" class="btn btn-primary" id="saveMensagem" onclick="addItem();" data-bs-dismiss="modal">Salvar</button>
</div>
</div>
</div>
</div>
</div>
<br />
</div>
</div>
JavaScript:
<script defer>
function updateSelect() {
const select = document.querySelector('#mensagem');
const oldMessage = JSON.parse(localStorage.getItem('mensagem')) || false;
if (oldMessage) {
select.innerHTML = '';
oldMessage.forEach(element => {
select.innerHTML += `<button class='dropdown-item' type='button'>${element}</option>`
});
} else {
localStorage.setItem('mensagem', '[]')
}
}
function addItem() {
const text = document.getElementById('txtMensagem').value;
const database = JSON.parse(localStorage.getItem('mensagem')) || [];
if (database && text.length > 3) {
const repetido = database.find(item => item === text.value);
if (!repetido) {
const novasMensagens = [...database, text];
localStorage.setItem('mensagem', JSON.stringify(novasMensagens))
updateSelect();
text.value = ''
}
}
}
updateSelect()
</script>
LINKS:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" type="text/javascript"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Had to change in order to solve my issue (which I still don't know):
function getMensagem() {
let valueMensagem = document.getElementById('mensagem').value;
if (valueMensagem != 0) {
$('select option:selected').each(function (e) {
$('#ContentPlaceHolder1_ddMensagensCopy').val(valueMensagem);
});
}
else {
$('#ContentPlaceHolder1_ddMensagensCopy').val('');
}
}
function updateSelectMensagem() {
const select = document.querySelector('#mensagem');
const oldMessage = JSON.parse(localStorage.getItem('mensagem')) || false;
if (oldMessage) {
select.innerHTML = "<option value='0'> Selecione uma mensagem </option>";
oldMessage.forEach(element => {
select.innerHTML += `<option class='dropdown-item'>${element}</option>`
});
} else {
localStorage.setItem('mensagem', '[]')
}
}
function addItemMensagem() {
const text = document.getElementById('txtMensagem').value;
const database = JSON.parse(localStorage.getItem('mensagem')) || [];
if (database && text.length > 3) {
const repetido = database.find(item => item === text.value);
if (!repetido) {
const novasMensagens = [...database, text];
localStorage.setItem('mensagem', JSON.stringify(novasMensagens))
updateSelectMensagem();
text.value = ''
}
}
}
updateSelectMensagem()
<div class="col-4">
<div class="dropdown-boleto">
<select id="mensagem" class="btn btn-secondary select">
<option value="0">Selecione uma mensagem</option>
</select>
</div>
</div>
.select option {
background: white;
color: #212529;
}
In fact, everything works as expected
https://codesandbox.io/s/shy-cookies-1xt96?file=/index.html
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.
I am working in Angular Js . I am trying to create a Login System from Sql Database based on username and password. I enter the right username and password but this do not go to page I want to redirect user home page but I can not do it . I got following error when I submit username and password into textbox from Console Application ....
angular.min.js:123 Error: [$injector:unpr] http://errors.angularjs.org/1.6.5/$injector/unpr?p0=myServiceProvider%20%3C-%20myService%20%3C-%20myCntrl
at angular.min.js:7
at angular.min.js:46
at Object.d [as get] (angular.min.js:43)
at angular.min.js:46
at d (angular.min.js:43)
at e (angular.min.js:44)
at Object.invoke (angular.min.js:44)
at O.instance (angular.min.js:94)
at q (angular.min.js:69)
at f (angular.min.js:62)
Here is my Module.Js Code...
var app = angular.module("myApp", [])
.controller("myCntrl", function ($scope, myService) {
$scope.LoginCheck = function () {
var User = {
UserName: $scope.uName,
Password: $scope.password
};
$("#divLoading").show();
var getData = myService.UserLogin(User);
getData.then(function (msg) {
if (msg.data == "0") {
$("#divLoading").hide();
$("#alertModal").modal('show');
$scope.msg = "Password Incorrect !";
}
else if (msg.data == "-1") {
$("#divLoading").hide();
$("#alertModal").modal('show');
$scope.msg = "Username Incorrect !";
}
else {
uID = msg.data;
$("#divLoading").hide();
window.location.href = "/Home/Index";
}
});
debugger;
}
function clearFields() {
$scope.uName = '';
$scope.uPwd = '';
}
//move this function inside `myCntrl` controller function.
$scope.alertmsg = function () {
$("#alertModal").modal('hide');
};
});
app.service("myService", function ($http) {
this.UserLogin = function (User) {
var response = $http({
method: "post",
url: "/Login/Login",
data: JSON.stringify(User),
dataType: "json"
});
return response;
}
});
Here is Login Controller Code ..
public class LoginController : Controller
{// GET: /Login/
public ActionResult Login()
{
return View();
}
[HttpPost]
public string Login(UserLogin data)
{
bool isPasswordCorrect = false;
string un = data.UserName;
string Password = data.Password;
using (HalifaxDatabaseEntities entity = new HalifaxDatabaseEntities())
{
var user = entity.UserLogins.Where(u => u.UserName == un).FirstOrDefault();
if (user != null)
{
if (Password == user.Password)
{
Session["LoginID"] = user.ID;
Session["Username"] = user.Firstname + ' ' + user.Lastname;
return user.ID.ToString();
}
else
{
return "0";
}
}
else
{
return "-1";
}
}
}
}
}
Here is my HTML CODE ....
#{
Layout = null;
}
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title></title>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/LoginScript/Module.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/Site.css" rel="stylesheet" />
<link href="~/Content/ui-bootstrap-csp.css" rel="stylesheet" />
</head>
<body>
<div ng-controller="myCntrl">
<h1>
<img src="~/Content/images/Loginicon.png" />
</h1>
<br />
<div id="alertModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<!-- dialog body -->
<div class="modal-body">
<button type="button" id="btn" value="Close" class="close" data-dismiss="modal">×</button>
{{msg}}
</div>
<!-- dialog buttons -->
<div class="modal-footer">
<button type="button" ng-click="alertmsg()" class="btn btn-primary">OK</button>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<div class="panel panel-success" style="width: 50%;">
<div class="panel-heading">Login</div>
<div class="panel-body" style="box-shadow: -6px 2px 46px 7px #888888; padding: 20px;">
<form name="loginForm" novalidate>
<div class="form-horizontal">
<div class="form-group">
<div class="row">
<div class="col-md-3" style="text-align: right;">
Username :
</div>
<div class="col-md-6">
<div class="input-group">
<input type="text" class="form-control" id="Uname" placeholder="Username" ng-model="uName" name="Username" required autofocus />
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-3" style="text-align: right;">
Password :
</div>
<div class="col-md-6">
<div class="input-group">
<input type="password" class="form-control" id="password" placeholder="Password" ng-model="password" name="Password" required autofocus />
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-6">
<div id="divLoading" style="margin: 0px; padding: 0px; position: fixed; right: 0px; top: 0px; width: 100%; height: 100%; background-color: #666666; z-index: 30001; opacity: .8; filter: alpha(opacity=70); display: none">
<p style="position: absolute; top: 30%; left: 45%; color: White;">
please wait...<img src="~/Content/images/load.png">
</p>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-5" style="text-align: right;">
<button id="btnLogin" type="submit" class="btn btn-success" ng-disabled="!(password && uName)" ng-click="LoginCheck()">Login</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Here is Solution Explorer Screen Shot...
Here is the screen shot when I lunch developer tools....
You have declared alertmsg outside controller function. Move it inside a myCntrl controller factory function. So basically because of $scope.alertmsg function kept outside $scope variable isn't defined, that's why JS compiler yelling there. And further statement aren't get executed. Since myService service doesn't get register in myApp angular module and it says myService unknown provider
http://errors.angularjs.org/1.6.5/$injector/unpr?p0=myServiceProvider%20%3C-%20myService
var app = angular.module("myApp", [])
.controller("myCntrl", function ($scope, myService) {
$scope.LoginCheck = function () {
//code as is
}
function clearFields() {
$scope.uName = '';
$scope.uPwd = '';
}
//move this function inside `myCntrl` controller function.
$scope.alertmsg = function () {
$("#alertModal").modal('hide');
};
});
Apart from angularjs errors, you have fix all the error appearing in
console. Likewise load jQuery before bootstrap.js
I am trying to integrate a payment gateway on a webpage using the stripe API. I am referring to this code snippet HERE. I am having trouble with loading JQUERY and kind of been struggling for some time to get it working. I am getting this error
Uncaught TypeError: Cannot read property 'addMethod' of undefined
I think the problem is because of not loading the jquery properly but not sure where its going wrong.
code
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<style>
/* Padding - just for asthetics on Bootsnipp.com */
body { margin-top:20px; }
/* CSS for Credit Card Payment form */
.panel-title {display: inline;font-weight: bold;}
.checkbox.pull-right { margin: 0; }
.pl-ziro { padding-left: 0px; }
.form-control.error {
border-color: red;
outline: 0;
box-shadow: inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(255,0,0,0.6);
}
label.error {
font-weight: bold;
color: red;
padding: 2px 8px;
margin-top: 2px;
}
.payment-errors {
font-weight: bold;
color: red;
padding: 2px 8px;
margin-top: 2px;
}
</style>
</head>
<div class="container">
<div class="row">
<div class="col-xs-12 col-md-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><img class="pull-right" src="http://i76.imgup.net/accepted_c22e0.png">Payment Details</h3>
</div>
<div class="panel-body">
<form role="form" id="payment-form">
<div class="row">
<div class="col-xs-12">
<div class="form-group">
<label for="cardNumber">CARD NUMBER</label>
<div class="input-group">
<input type="text" class="form-control" name="cardNumber" placeholder="Valid Card Number" required autofocus data-stripe="number" />
<span class="input-group-addon"><i class="fa fa-credit-card"></i></span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-7 col-md-7">
<div class="form-group">
<label for="expMonth">EXPIRATION DATE</label>
<div class="col-xs-6 col-lg-6 pl-ziro">
<input type="text" class="form-control" name="expMonth" placeholder="MM" required data-stripe="exp_month" />
</div>
<div class="col-xs-6 col-lg-6 pl-ziro">
<input type="text" class="form-control" name="expYear" placeholder="YY" required data-stripe="exp_year" />
</div>
</div>
</div>
<div class="col-xs-5 col-md-5 pull-right">
<div class="form-group">
<label for="cvCode">CV CODE</label>
<input type="password" class="form-control" name="cvCode" placeholder="CV" required data-stripe="cvc" />
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="form-group">
<label for="couponCode">COUPON CODE</label>
<input type="text" class="form-control" name="couponCode" />
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<button class="btn btn-success btn-lg btn-block" type="submit">Start Subscription</button>
</div>
</div>
<div class="row" style="display:none;">
<div class="col-xs-12">
<p class="payment-errors"></p>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script>
var $form = $('#payment-form');
$form.on('submit', payWithStripe);
/* If you're using Stripe for payments */
function payWithStripe(e) {
e.preventDefault();
/* Visual feedback */
$form.find('[type=submit]').html('Validating <i class="fa fa-spinner fa-pulse"></i>');
var PublishableKey = 'mykey'; // Replace with your API publishable key
Stripe.setPublishableKey(PublishableKey);
Stripe.card.createToken($form, function stripeResponseHandler(status, response) {
console.log
if (response.error) {
/* Visual feedback */
$form.find('[type=submit]').html('Try again');
/* Show Stripe errors on the form */
$form.find('.payment-errors').text(response.error.message);
$form.find('.payment-errors').closest('.row').show();
} else {
/* Visual feedback */
$form.find('[type=submit]').html('Processing <i class="fa fa-spinner fa-pulse"></i>');
/* Hide Stripe errors on the form */
$form.find('.payment-errors').closest('.row').hide();
$form.find('.payment-errors').text("");
// response contains id and card, which contains additional card details
var token = response.id;
console.log(token);
// AJAX
$.post('/account/stripe_card_token', {
token: token
})
// Assign handlers immediately after making the request,
.done(function(data, textStatus, jqXHR) {
$form.find('[type=submit]').html('Payment successful <i class="fa fa-check"></i>').prop('disabled', true);
})
.fail(function(jqXHR, textStatus, errorThrown) {
$form.find('[type=submit]').html('There was a problem').removeClass('success').addClass('error');
/* Show Stripe errors on the form */
$form.find('.payment-errors').text('Try refreshing the page and trying again.');
$form.find('.payment-errors').closest('.row').show();
});
}
});
}
/* Form validation */
jQuery.validator.addMethod("month", function(value, element) {
return this.optional(element) || /^(01|02|03|04|05|06|07|08|09|10|11|12)$/.test(value);
}, "Please specify a valid 2-digit month.");
jQuery.validator.addMethod("year", function(value, element) {
return this.optional(element) || /^[0-9]{2}$/.test(value);
}, "Please specify a valid 2-digit year.");
validator = $form.validate({
rules: {
cardNumber: {
required: true,
creditcard: true,
digits: true
},
expMonth: {
required: true,
month: true
},
expYear: {
required: true,
year: true
},
cvCode: {
required: true,
digits: true
}
},
highlight: function(element) {
$(element).closest('.form-control').removeClass('success').addClass('error');
},
unhighlight: function(element) {
$(element).closest('.form-control').removeClass('error').addClass('success');
},
errorPlacement: function(error, element) {
$(element).closest('.form-group').append(error);
}
});
paymentFormReady = function() {
if ($form.find('[name=cardNumber]').hasClass("success") &&
$form.find('[name=expMonth]').hasClass("success") &&
$form.find('[name=expYear]').hasClass("success") &&
$form.find('[name=cvCode]').val().length > 1) {
return true;
} else {
return false;
}
}
$form.find('[type=submit]').prop('disabled', true);
var readyInterval = setInterval(function() {
if (paymentFormReady()) {
$form.find('[type=submit]').prop('disabled', false);
clearInterval(readyInterval);
}
}, 250);
</script>
Your problem is that:
You are trying to use this jquery validation plugin without including it to your page.
add this to your page
<script type="text/javascript" src="http://cdn.jsdelivr.net/jquery.validation/1.13.1/jquery.validate.min.js"></script>
DEMO