Keeping Modal Form Open After Failed Submission Attempt - javascript

I am working on a Nodejs project and currently working on making a modal form stay open after a user fails to meet form requirements, such as filling out all the form fields. I've done some reading online and am having trouble understanding how I would do this. Currently, I just have the form render a new page when there is a mistake completing the form. The repo to this project is: https://github.com/halsheik/RecipeWarehouse.git. Below, I have also pasted the relevant chunks of my code for this problem. I would appreciate any assistance.
// Modules required to run the application
const express = require('express');
const multer = require('multer');
const crypto = require('crypto');
const path = require('path');
const { ensureAuthenticated } = require('../config/auth');
// Creates 'mini app'
const router = express.Router();
// Models
const Recipe = require('../models/Recipe'); // Recipe Model
// Set up storage engine
const storage = multer.diskStorage({
destination: function(req, file, callback){
callback(null, 'public/uploads');
},
filename: function(req, file, callback){
crypto.pseudoRandomBytes(16, function(err, raw) {
if (err) return callback(err);
callback(null, raw.toString('hex') + path.extname(file.originalname));
});
}
});
const upload = multer({
storage: storage
});
// My Recipes
router.get('/myRecipes', ensureAuthenticated, function(req, res){
Recipe.find({}, function(err, recipes){
if(err){
console.log(err);
} else {
res.render('./home/myRecipes', {
recipes: recipes,
recipeImageFileName: recipes.recipeImageFileName,
recipeDescription: recipes.recipeDescription,
ingredients: recipes.ingredients,
directions: recipes.directions
});
}
});
});
// Create Recipe
router.post('/createRecipe', upload.single('recipeImage'), ensureAuthenticated, function(req, res){
const { recipeName, recipeDescription, ingredients, directions } = req.body;
let errors = [];
// Checks that all fields are not empty
if(!recipeName || !recipeDescription || !ingredients || !directions){
errors.push({ msg: 'Please fill in all fields.' });
}
// Checks that an image is uploaded
if(!req.file){
errors.push({ msg: 'Please add an image of your recipe' });
}
// Checks for any errors and prevents recipe creation if any
if(errors.length > 0){
console.log(errors);
Recipe.find({}, function(err, recipes){
if(err){
console.log(err);
} else {
res.render('./home/myRecipes', {
errors: errors,
recipes: recipes,
recipeImageFileName: recipes.recipeImageFileName,
recipeDescription: recipes.recipeDescription,
ingredients: recipes.ingredients,
directions: recipes.directions
});
}
});
} else {
// Create a new 'Recipe' using our model
const newRecipe = new Recipe({
recipeName: recipeName,
author: req.user._id,
recipeImageFileName: req.file.filename,
recipeDescription: recipeDescription,
ingredients: ingredients,
directions: directions,
});
console.log(newRecipe);
// Saves recipe to mongoDB database
newRecipe.save().then(function(){
res.redirect('/recipes/myRecipes');
}).catch(function(err){
console.log(err);
});
}
});
module.exports = router;
<%- include('../_partial/_header'); -%>
<div id="newRecipeContainer">
<div class="overlay"></div>
<div id="closeButtonContainer">
<div id="closeButton">+</div>
</div>
<form action="/recipes/createRecipe" method="POST" enctype="multipart/form-data">
<label id="formSubHeading">Create Your Homemade Recipe</label>
<div id="recipeNameContainer">
<label id="recipeNameLabel">Title</label>
<input id="recipeNameInput" type="text" name="recipeName">
</div>
<div id="recipeImage">
<label id="recipeImageLabel">Add An Image of Your Meal</label>
<input id="recipeImageInput" type="file" accept="image/*" name="recipeImage" onchange="validateImageFile(this);"/>
<label id="recipeImageInputLabel" for="recipeImageInput">Choose A File</label>
</div>
<div id="recipeDescription">
<label id="recipeDescriptionLabel">Description</label>
<textarea id="recipeDescriptionInput" name="recipeDescription" cols="30" rows="10" maxlength="2000"></textarea>
</div>
<div class="ingredientsContainer">
<label id="ingredientsLabel">Ingredients</label>
<button id="addIngredientButton" type="button" #click="addIngredientForm">Add Another Ingredient</button>
<div class="allIngredients" v-for="(ingredient, ingredientIndex) in ingredients">
<label class="ingredientLabel">{{ ingredientIndex + 1 }}.)</label>
<input class="ingredientInput" type="text" name="ingredients" v-model="ingredient.ingredient">
<button class="deleteIngredientButton" type="button" v-if="ingredientIndex > 0" #click="deleteIngredientForm(ingredientIndex)">X</button>
</div>
</div>
<div class="directionsContainer">
<label id="directionsLabel">Directions</label>
<button id="addDirectionButton" type="button" #click="addDirectionForm">Add Another Direction</button>
<div class="allDirections" v-for="(direction, directionIndex) in directions">
<label class="directionLabel">{{ directionIndex + 1 }}.)</label>
<input class="directionInput"type="text" name="directions" v-model="direction.direction">
<button class="deleteDirectionButton" type="button" v-if="directionIndex > 0" #click="deleteDirectionForm(directionIndex)">X</button>
</div>
</div>
<div id="createRecipeButtonContainer">
<button id="createRecipeButton" type="submit">Create Recipe</button>
</div>
</form>
</div>
<div id="recipesContainer">
<div id="myRecipesContainer">
<label id="myRecipesLabel">My Recipes</label>
<a id="newRecipeButton">+ Create New Recipe</a>
</div>
<div id="allRecipes">
<% recipes.forEach(function(recipe){ %>
<% if(recipe.author == user._id){ %>
<div class="secondaryContainer">
<div class="recipeContainerIndv">
<img src="/uploads/<%= recipe.recipeImageFileName %>"/>
<a class="recipeTitle"> <%= recipe.recipeName %> </a>
<!-- <% recipe.directions.forEach(function(direction){ %>
<a><%= direction %></a>
<% }); %> -->
</div>
</div>
<% } %>
<% }); %>
</div>
</div>
<script src="/controls/newRecipeControl.js"></script>
<script src="/controls/imageValidator.js"></script>
<%- include('../_partial/_footer'); -%>
const directionsControl = new Vue({
el: '.directionsContainer',
data: {
directions: [
{
direction: ''
}
]
},
methods: {
addDirectionForm: function(){
this.directions.push({
direction: ''
})
},
deleteDirectionForm: function(directionIndex){
if(directionIndex)
this.directions.splice(directionIndex, 1)
}
}
})
const ingredientsControl = new Vue({
el: '.ingredientsContainer',
data: {
ingredients: [
{
ingredient: ''
}
]
},
methods: {
addIngredientForm: function(){
this.ingredients.push({
ingredient: ''
})
},
deleteIngredientForm: function(ingredientIndex){
if(ingredientIndex)
this.ingredients.splice(ingredientIndex, 1)
}
}
})
const toggleNewRecipeForm = function(){
const newRecipeButton = document.querySelector('#newRecipeButton');
const newRecipeContainer = document.querySelector('#newRecipeContainer');
const closeButton = document.querySelector('#closeButton');
const overlay = document.querySelector('.overlay');
// Open dropDownMenu
newRecipeButton.addEventListener('click', function(){
newRecipeContainer.style.display = 'block';
overlay.classList.toggle('addOverlay');
});
// Close dropDownMenu
closeButton.addEventListener('click', function(){
newRecipeContainer.style.display = 'none';
overlay.classList.toggle('addOverlay');
});
}
toggleNewRecipeForm();

To keep the hole page from refreshing you would have to look into client-side frameworks I would recommend learning AngularJS it would make you able to refresh the form without refreshing the page.

I would also recommend some client-side framework, in my case i use bootstrap and jquery in this way:
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$('button[value=save]').click(function(e) {
e.preventDefault();
// ....
// Code to check validity
// ....
// Hides modal
$('#exampleModal').modal('hide');
});
});
</script>

Related

I am trying to create a bug/issue tracker. It works in the web browser but I am trying to deploy with node server and the app does not work anymore

My app works in live server but when i add nodejs, it doesn't work correctly. The Modal window does not pop up anymore and I do not know why. I have understood that I cant use localstorage or window properties because it is not on the browser anymore, but I cant figure out what to do instead of using those. Is there an npm package I can install to use localstorage and other browser side properties? Just looking for someone to point out my mistake and point me in the right direction. Any help is greatly appreciated. Thanks in advance!
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD"
crossorigin="anonymous">
<script src="https://kit.fontawesome.com/4582c8b826.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="/css/styles.css">
<title>Issue Tracker</title>
</head>
<body>
<div class="contaienr">
<h1>Issue Tracker</h1>
<div class="jumbotron">
<h3>Add New Issue:</h3>
<form id="issueinputform">
<div class="form-group">
<label for="issueDescription">Description</label>
<input type="text" class="form-control" id="issueDescription" placeholder="Describe the issue ...">
</div>
<div class="form-group">
<label for="issueSeverity">Severity</label>
<select class="form-control" id="issueSeverity">
<option value="Low">Low</option>
<option value="Medium">Medium</option>
<option value="High">High</option>
</select>
</div>
<div class="form-group">
<label for="issueAssignedTo">Assigned To</label>
<input type="text" class="form-control" id="issueAssignedTo" placeholder="Enter responsible ...">
</div>
<button id="add-issue" onclick="submitIssue()" class="btn btn-primary">Add</button>
</form>
</div>
<div class="col-lg-12">
<div id="issuesList">
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="emptyField" tabindex="-1" role="dialog" aria-labelledby="emptyFieldLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="emptyFieldLabel">Invalid Input!</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Please provide the desciption of the issue and also the person name who you want to assign the issue.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script src="app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/js/bootstrap.min.js" integrity="sha384-mQ93GR66B00ZXjt0YO5KlohRA5SY2XofN4zfuZxLkoj1gXtW8ANNCe9d5Y3eG5eD" crossorigin="anonymous"></script>
</body>
</html>
app.js
function submitIssue(e) {
const getInputValue = id => document.getElementById(id).value;
const description = getInputValue('issueDescription');
const severity = getInputValue('issueSeverity');
const assignedTo = getInputValue('issueAssignedTo');
const id = Math.floor(Math.random() * 100000000) + '';
const status = 'Open';
if ((description.length == 0) || (assignedTo.length == 0)) {
alert("Please fill all fields with required data.");
document.getElementById('add-issue').setAttribute("data-toggle", "modal");
document.getElementById('add-issue').setAttribute("data-target", "#emptyField")
}
else {
document.getElementById('add-issue').removeAttribute("data-toggle", "modal");
document.getElementById('add-issue').removeAttribute("data-target", "#emptyField")
const issue = { id, description, severity, assignedTo, status };
let issues = [];
if (localStorage.getItem('issues')) {
issues = JSON.parse(localStorage.getItem('issues'));
}
issues.push(issue);
localStorage.setItem('issues', JSON.stringify(issues));
fetchIssues();
}
}
const closeIssue = id => {
const issues = JSON.parse(localStorage.getItem('issues'));
const currentIssue = issues.find(issue => issue.id == id);
currentIssue.status = 'Closed';
currentIssue.description = `<strike>${currentIssue.description}</strike>`
localStorage.setItem('issues', JSON.stringify(issues));
fetchIssues();
}
const deleteIssue = id => {
const issues = JSON.parse(localStorage.getItem('issues'));
const remainingIssues = issues.filter(issue => ((issue.id) != id))
localStorage.removeItem('issues');
localStorage.setItem('issues', JSON.stringify(remainingIssues));
fetchIssues();
}
const fetchIssues = () => {
const issues = JSON.parse(localStorage.getItem('issues'));
const issuesList = document.getElementById('issuesList');
issuesList.innerHTML = '';
for (let i = 0; i < issues.length; i++) {
const { id, description, severity, assignedTo, status } = issues[i];
issuesList.innerHTML += `<div class="well">
<h6>Issue ID: ${id} </h6>
<p><span class="label label-info"> ${status} </span></p>
<h3> ${description} </h3>
<p><i class="fa-solid fa-bolt"></i> ${severity}</p>
<p><i class="fa-solid fa-user"></i> ${assignedTo}</p>
<button onclick="closeIssue(${id})" class="btn btn-warning">Close</button>
<button onclick="deleteIssue(${id})" class="btn btn-danger">Delete</button>
</div>`;
}
}
fetchIssues();
main.js(server)
const bodyParser = require('body-parser');
const express = require('express');
const mongoose = require('mongoose');
const ejs = require('ejs')
const app = express();
const path = require('path');
const morgan = require('morgan')
const bcrypt = require('bcrypt');
const saltRounds = 10;
app.use(express.static('public'));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(morgan('tiny'))
mongoose.connect("mongodb://localhost:27017/userDB", {useNewUrlParser: true});
const userSchema = new mongoose.Schema ({
email: String,
password: String
});
const User = new mongoose.model("User", userSchema)
app.get('/', function(req,res){
// res.sendFile(path.join(__dirname, '/index.html'));
res.redirect('/login')
});
app.get('/login', function (req,res){
// res.sendFile(path.join(__dirname, '/login/login.html'));
res.render('login')
})
app.get('/register', function(req,res){
res.render("register")
});
app.post('/register', function(req,res){
bcrypt.hash(req.body.password, saltRounds, function(err,hash) {
const newUser = new User({
email: req.body.username,
password: hash
});
newUser.save(function(err){
if(err){
console.log(err)
} else{
res.sendFile(path.join(__dirname+'/home.html'));
}
});
});
});
app.get('/home', function(req,res){
res.sendFile(path.join(__dirname+'/home.html'));
// appSubmit.submitIssue()
})
// app.get('/home?', function(req,res){
// // res.sendFile(path.join(__dirname+'/home.html'));
// appSubmit.submitIssue();
// })
app.post('/login', function(req,res){
const username = req.body.username;
const password = req.body.password;
User.findOne({email: username}, function(err,foundUser){
if(err){
console.log(err)
} else{
if(foundUser){
bcrypt.compare(password, foundUser.password, function(err, result) {
// res.sendFile(path.join(__dirname+'/home.html'));
res.redirect('/home')
});
}
}
})
})
app.listen(5000,function(){
console.log("server runnin on 5000")
})

Razor Communicate Display of Modal from PageModel's OnPost() Method

I want to communicate from my Razor PageModel's OnPost() method to display the modal upon validation errors for it. Which basically means changing the modal's css from display none to block. Is there a way for this to be done?
Currently on return Page() the modal is hidden because thats what its css is initially set to, and is normally displayed on the user clicking the button to show it. I marked in my PageModel code where Id like the communication to occur
#page
#{
ViewData["Folder"] = "CourtUser";
<form asp-action="AddorEditUsersOnHearing" method="post" name="AddorEditUsersOnHearingForm" id="AddorEditUsersOnHearing">
<div class="container">
<div class="row">
<div class="col-md-8 mb-4">
<p>Add/Edit Users on <b style="font-style:italic">#Model.HearingName </b></p>
<div class="modal" tabindex="-1" role="dialog" id="AddUserForm">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Add User</h5>
<button type="button" onclick="closeAddUserForm()" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="form-group" style="margin-top:5px;padding-left:45px">
<label asp-for="AddUserInput" style="width:100px"></label>
<input asp-for="AddUserInput" class="form-control col-4" id="EmailInputBox" style="display:inline-block" onchange="ValidateEmail()" />
<span style="display:block" asp-validation-for="AddUserInput" class="text-danger"></span>
</div>
<div class="modal-footer">
<button class="btn btn-primary" style="margin:0 auto" asp-page-handler="AddUser" name="AddUserSubmit" value="Yes">Submit</button>
</div>
</div>
</div>
</div>
<input asp-for="HearingId" type="hidden" />
<input asp-for="HearingName" type="hidden" />
<button type="button" class="btn btn-primary" onclick="ShowAddUserForm()">Add User</button>
<button style="float:right" class="btn btn-primary">Remove User(s)</button>
</div>
</div>
</div>
</form>
}
<script type="text/javascript">
function ShowAddUserForm() {
document.getElementById("AddUserForm").style.display = "block";
}
function closeAddUserForm() {
document.getElementById("AddUserForm").style.display = "none";
}
</script>
public IActionResult OnPostAddUser()
{
if (ModelState.IsValid)
{
if (AddUserInput == null)
{
ModelState.AddModelError("AddUserInput", "Please enter an email");
UsersonHearingList = HttpContext.Session.GetObjectFromJson<List<UsersModel>>("UsersonHearingList");
//*****This is where I want to communicate to the view to display the modal.*******
return Page();
}
}
else
{
return RedirectToPage("/Shared/Error");
}
}
You can try to use TempData.Here is a demo:
js:
#section Scripts
{
<script type="text/javascript">
$(function () {
if ("#TempData["Modal"]" == "Display")
{
ShowAddUserForm();
}
});
function ShowAddUserForm() {
document.getElementById("AddUserForm").style.display = "block";
}
function closeAddUserForm() {
document.getElementById("AddUserForm").style.display = "none";
}
</script>
}
handler:
public IActionResult OnPostAddUser()
{
if (ModelState.IsValid)
{
if (AddUserInput == null)
{
ModelState.AddModelError("AddUserInput", "Please enter an email");
UsersonHearingList = HttpContext.Session.GetObjectFromJson<List<UsersModel>>("UsersonHearingList");
//*****This is where I want to communicate to the view to display the modal.*******
TempData["Modal"] = "Display";
return Page();
}
}
else
{
return RedirectToPage("/Shared/Error");
}
}
result:

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

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

I want to show ModalDialogbox to clients when Clients click on resetlink

I am doing resetpassword system in Meteor,I want to show ModalDialogbox to clients when Clients click on resetlink but couldn't do it.
account.html
this is my ResetPasswordform and Modal
<template name="ResetPassword">
{{#if resetPassword}}
<div class="modal fade" id="myModal-9" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<span class="f-s-20 text-blue">ŞİFRE DEĞİŞTİRME EKRANI </span>
</div>
<div class="modal-body">
<form action="/reset-password" id="resetPasswordForm" method="post">
<div class="form-group">
<input id="resetPasswordPassword" type="password" name="newpassword" class="form-control width-250 m-auto" placeholder="Yeni Şifrenizi Girin">
</div>
<div class="form-group">
<input id="resetPasswordPasswordConfirm" type="password" name="newpasswordconfirm" class="form-control width-250 m-auto" placeholder="Yeni şifre tekrarla">
</div>
<div class="form-group">
<button type="button" id="resetpasswordbtn" class="btn btn-theme width-250" value="Reset">Yenile</button>
</div>
</form>
</div>
</div>
</div>
</div>
{{/if}}
</template>
account.js
if (Accounts._resetPasswordToken) {
Session.set('resetPassword', Accounts._resetPasswordToken);
}
Accounts.onResetPasswordLink(function (token, done) {
Session.set('resetPassword', token); meteo
done(); // Assigning to variable
$t.find('#myModal-9').modal('show');
});
Template.ResetPassword.helpers({
resetPassword: function () {
return Session.get('resetPassword');
}
});
I use bootbox to display bootstrap-style modals in Meteor, using Meteor templates (so that the modals are reactive). If you
meteor add mizzao:bootboxjs
Then the following function will suffice to display a modal:
function displayModal(template, data, options) {
// minimum options to get message to show
options = options || { message: " " };
var dialog = bootbox.dialog(options);
// Take out the default body that bootbox rendered
dialog.find(".bootbox-body").remove();
// Insert a Meteor template
// Since bootbox/bootstrap uses jQuery, this should clean up itself upon removal
Blaze.renderWithData(template, data, dialog.find(".modal-body")[0]);
return dialog;
}
You'll find that the default bootbox modals are also useful for non-reactive messages.

Cannot link back to MVC view via javascript

I have an Index View and when I click the Edit button, I post to the Edit View (via the Controller) and display a bootstrap modal popup.
By posting to the Edit View, the Controller/View automatically handle getting and displaying the correct data on the modal popup.
Once I'm on my Edit View with the dialog box appearing and I click on the Close button, I simply want to link back to the Index page again; but instead, am getting an error with the path of the url. The new path I want to link to is being "tacked on" to the original path instead of replacing it.
I'm using the Url.Action method inside the click event of the Close button (of which I verified it's hitting) and have verified the location.href url is exactly what is in the url variable as you see in the code.
What do I need to do to correctly link back to the Index url?
Index View
<span class="glyphicon glyphicon-edit" aria-hidden="true"></span>Edit
Edit Controller
// GET: Categories/Edit/5
public async Task<ActionResult> Edit(short id)
{
if (id == 0)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Category category = await db.GetCategoryIDAsync(id);
if (category == null)
{
return HttpNotFound();
}
return View(category);
}
Edit View
#model YeagerTechDB.Models.Category
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="modal" id="categoryEditModal" tabindex="-1" role="dialog" aria-labelledby="categoryModal-label" aria-hidden="true">
<div class="modal-dialog">
<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="categoryModal-label">Category Description</h4>
</div>
<div class="modal-body">
<div class="form-group">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CategoryDescription, new { #class = "control-label required col-offset-1 col-lg-3 col-md-3 col-sm-3 col-xs-3" })
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8">
#Html.EditorFor(model => model.CategoryDescription, new { #class = "form-control" } )
#Html.ValidationMessageFor(model => model.CategoryDescription, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default" id="btnCloseCategory">Close</button>
<button type="submit" class="btn btn-primary" id="btnSaveCategory">Save</button>
</div>
</div>
</div>
</div>
<div>
#Html.Hidden("categoryEditUrl", Url.Action("Edit", "Category", new { area = "Categories" }))
#Html.Hidden("catID", Model.CategoryID)
</div>
#section Scripts {
<script>
$(document).ready(function ()
{
if (typeof contentEditCategory == "function")
contentEditCategory()
});
</script>
}
JS for Edit View
$('#btnCloseCategory').click(function (e)
{
var url = '#Url.Action("Index", "Category", new { area = "Categories" })';
location.href = url;
return false;
});
Image of modal popup
Image of error
Assuming your javascript is in an external file you could do the following:
Attach the url to your button within your view with a data attribute as follows:
<button type="submit" class="btn btn-default" id="btnCloseCategory"
data-url="#Url.Action("Index", "Category", new { area = "Categories" })">Close</button>
Then pull back the url with the data method as follows:
$('#btnCloseCategory').click(function (e)
{
var url = $(this).data('url');
location.href = url;
return false;
});
Try changing type="submit" to type="button" for your Close button.
<button type="button" class="btn btn-default" id="btnCloseCategory">Close</button>

Categories