Trouble using multiple bootstrap modals (ngx-bootstrap and Angular) - javascript

I really have a problem using multiple bootstrap modals within Angular 4. Maybe you can help me out of this. The code is working fine with just one modal. I am not be able to use the buttons/form of the first loaded modal. The second is working fine. After opening and closing the second modal, also the first modal works... strange. Is there something wrong?
<!-- ADD MODAL-->
<div bsModal #addModal="bs-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myAddModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add Dimension</h4>
<button type="button" class="close" (click)="addModal.hide()" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="formGroupInput">TAG</label>
<input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input" aria-describedby="keyHelp"
value="" disabled>
<small id="keyHelp" class="form-text text-muted">Notice that this field is a surrogate key!</small>
</div>
<div class="form-group">
<label for="formGroupInput2">Name</label>
<input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input" value="">
</div>
<div class="form-group">
<label for="formGroupInput3">Description</label>
<input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input" value="">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="dfsdfsdfsdf" class="btn btn-secondary" (click)="addModal.hide()">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<!-- EDIT MODAL-->
<div bsModal #editModal="bs-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Edit {{currentItem?.NAME}}</h4>
<button type="button" class="close" (click)="editModal.hide()" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="formGroupInput">TAG</label>
<input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input" aria-describedby="keyHelp"
value="{{currentItem?.TAG}}" disabled>
<small id="keyHelp" class="form-text text-muted">You'll need to delete this entry to change this key value!</small>
</div>
<div class="form-group">
<label for="formGroupInput2">Name</label>
<input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input" value="{{currentItem?.NAME}}">
</div>
<div class="form-group">
<label for="formGroupInput3">Description</label>
<input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input" value="{{currentItem?.COMM}}">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" (click)="editModal.hide()">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
import { Component, OnInit, ViewChild } from '#angular/core';
import { DataService } from "../data.service";
import { ModalDirective } from 'ngx-bootstrap/modal/modal.component';
#Component({
templateUrl: './dimensions.component.html',
styleUrls: ['./dimensions.component.scss']
})
export class DimensionsComponent implements OnInit {
#ViewChild('editModal') public editModal: ModalDirective;
#ViewChild('addModal') public addModal: ModalDirective;
currentItem;
openModal(item: any) {
this.currentItem = item;
this.editModal.show();
}
openAddModal() {
this.addModal.show();
}
//Attributes
public currentVar;
subscription;
dimensionData;
rows;
constructor(private _dataService: DataService) {
}
Thank you for your time guys!
Update: By switching the modal sequence inside the code the problem also occures but just in terms of the other modal.

bsModal directive is not really suited for nested modals, please convert to usage of bsModal service, see example here:
https://valor-software.com/ngx-bootstrap/#/modals#service-nested

So after a few fixes, production use and testings I can say I have found a solution to a nested ngx-bootstrap modal problems. I have written a service-wrapper for a BsModalService.
modalIndexing = {};
hasInited = false;
constructor(
router: Router,
private modalService: BsModalService,
) {
router.events
.pipe(filter((event: NavigationEvent) => (event instanceof NavigationStart)))
.subscribe(() => this.terminateAll());
}
// Just a modal dude
resolveModal(component, position: 'center' | 'static' = 'center', initialState?: any): void {
const config: ModalOptions = {
class: modalClassDict[position] + ' ss-modal',
initialState
};
// For nested launches, wait until previous hide to open new
setTimeout(() => {
this.modalService.show(component, config);
}, initialState.hasTimeout ? 600 : 0);
}
// Modal dude that will return something
// if you want to of cause, no pressure
resolveModalSub(component, position: 'center' | 'static' = 'center', initialState?: any): Observable<any> {
const config: ModalOptions = {
class: modalClassDict[position] + ' ss-modal',
initialState
};
const bsModalRef = this.modalService.show(component, config);
bsModalRef.content.onClose = new Subject<any>();
const modalSub = bsModalRef.content.onClose.pipe(take(1));
this.healthCheck(modalSub);
return modalSub;
}
// This sneaky little bastard will return something if it hides!
resolveModalSubCheckHide(component, position: 'center' | 'static' = 'center', initialState?: any): Observable<any> {
const config: ModalOptions = {
class: modalClassDict[position] + ' ss-modal',
initialState
};
const bsModalRef = this.modalService.show(component, config);
bsModalRef.content.onClose = new Subject<any>();
const modalSub = bsModalRef.content.onClose.pipe(take(1));
this.healthCheck(modalSub, true);
return modalSub;
}
// This thingy does some pseudo-indexing and cleans up the mess you left
private healthCheck(modalSub, needToCheckHide = false) {
// The only property ngx-bootstrap modal service
// is able to return is the number of openned modals
// so we are heading out from it
const index = this.modalService.getModalsCount();
this.modalIndexing[index] = {
modalSub,
needToCheckHide
};
// First modal initiates onHide sub
if (!this.hasInited) {
this.hasInited = true;
this.modalService.onHide
.subscribe(() => {
if (_.keys(this.modalIndexing).length) {
// This event emits after the modal is closed so its a +1
const indexedSub = this.modalIndexing[this.modalService.getModalsCount() + 1];
// Handeles the case when you need to know if modal was closed
if (indexedSub.needToCheckHide) {
indexedSub.modalSub.next(false);
}
// Completes sub of a value return and cleans itself from dictionary
if (indexedSub.modalSub) {
indexedSub.modalSub.complete();
}
delete this.modalIndexing[this.modalService.getModalsCount() + 1];
}
});
}
}
// Termiantes all modal windows in user navigates via back / forward
private terminateAll() {
_.keys(this.modalIndexing).forEach(index => this.modalService.hide(index));
}
Basic usage:
const data = {
// your initial data
};
this.dialogService.resolveModalSubCheckHide(YourModalComponentToDisplay, 'center', data)
.subscribe((value) => {
// processing
});
Features:
Return value handling as subject
Performance friendly
Doesn`t leave any uncompleted subjects
Can return a value if hidden
Handles unlimited nested levels
Can be queued to launch modals
Auto close on manual navigation
Hope this helps somebody <3.

Related

Field not empty but the modal is displayed - Angular

I am learning Angular, I created in my page 3 fields: Article, Quantity, Limit.
If each field is empty, a modal appears !
For now, I have no problem, the modal appears like I want.
Now, I have two questions please:
1- If my fields are completed, and that the user clicks on OK, my modal appears ?? How to I change this ?
2- You think that it is possible for example that the field quantity to be completed obligatorily. For example, if the field quantity is completed and no the fields article and limit. There is no modal to display.
I am stuck on these two questions...
component.html
<br><br>
<label for='quantity'>Article</label>
<div class="input-group">
<input type="text" class="form-control" id="article" name="article">
</div>
<label for='quantity'>Quantity</label>
<div class="input-group">
<input type="number" class="form-control" id="quantity" name="quantity">
</div>
<label for='quantity'>Limit</label>
<div class="input-group">
<input type="number" class="form-control" id="orderLimit" name="orderLimit">
</div>
<br>
<div class="row">
<div class="col-12">
<button class="btn btn-lg btn-outline-primary" (click)="open(mymodal)"> ok </button>
</div>
</div>
<!-- Modal -->
<ng-template #mymodal let-modal>
<div class="modal-header">
<h4 class="modal-title" id="modal-basic-title">Error message</h4>
<button type="button" class="close" aria-label="Close button" aria-describedby="modal-title" (click)="modal.dismiss('Cross click')">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="table-responsive">
<table class="table table-striped">
<thead>
</thead>
<tbody>
<td>Fields cannot be empty</td>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-dark" (click)="modal.close('Save click')">Ok</button>
</div>
</ng-template>
component.ts
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'appBootstrap';
closeResult: string | undefined;
constructor(private modalService: NgbModal) {}
open(content: any) {
this.modalService
.open(content, { ariaLabelledBy: 'modal-basic-title' })
.result.then(
result => {
this.closeResult = `Closed with: ${result}`;
},
reason => {
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
}
);
}
private getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return 'by pressing ESC';
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return 'by clicking on a backdrop';
} else {
return `with: ${reason}`;
}
}
}
I can put my code below if you want:
https://stackblitz.com/edit/angular-ivy-kr7cyd?file=src/app/app.component.ts
1- If my fields are completed, and that the user clicks on OK, my
modal appears ?? How to I change this ?
No, It should not appear as you mentioned the modal should only open when the fields are empty.
2- You think that it is possible for example that the field quantity
to be completed obligatorily. For example, if the field quantity is
completed and no the fields article and limit. There is no modal to
display.
You can do that if you want. You can use ngModel and bind each input property that can help you track their values as soon as the user updates it. When you open or close the modal you can do it in the component method instead closing modal using the view reference variable.
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'appBootstrap';
article = 0, quantity = 0, orderLimit = 0;
closeResult: string | undefined;
constructor(private modalService: NgbModal) {}
open(content: any) {
this.modalService
.open(content, { ariaLabelledBy: 'modal-basic-title' })
.result.then(
result => {
this.closeResult = `Closed with: ${result}`;
},
reason => {
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
}
);
}
private getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return 'by pressing ESC';
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return 'by clicking on a backdrop';
} else {
return `with: ${reason}`;
}
}
// this should be checked everytime when user clicks 'Ok'
openModal() {
// check if the values are '0'
// make sure the values come in as Number
if (orderLimit && article && quantity) {
// show modal
} else {
// no need to show modal
}
}
}
<label for='quantity'>Article</label>
<div class="input-group">
<input type="text" class="form-control" id="article" name="article" [(ngModel)]="article">
</div>
<label for='quantity'>Quantity</label>
<div class="input-group">
<input type="number" class="form-control" id="quantity" [(ngModel)]="quantity" name="quantity">
</div>
<label for='quantity'>Limit</label>
<div class="input-group">
<input type="number" class="form-control" id="orderLimit" [(ngModel)]="orderLimit" name="orderLimit">
</div>

Page freeze after navigating from modal

Whenever I navigate from my modal component in VueJS to another route, the next page freezes until I refresh it.
Please what can I do to resolve this.
Below is my component code(The Template section).
<template>
<div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
<i data-feather="user"></i>Login
</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="#" class="vld-parent" ref="talentLogin">
<div class="form-group">
<input
type="email"
placeholder="Email Address"
class="form-control"
v-model="loginDetails.email"
/>
</div>
<div class="form-group">
<input
type="password"
placeholder="Password"
class="form-control"
v-model="loginDetails.password"
/>
</div>
<button type="button" #click="logIn" class="button primary-bg btn-block">Login</button>
<a href onclick="showResetPasssord" class="align-center">Reset Password</a>
</form>
<ResetPasswordModal ref="resetPasswordModal"></ResetPasswordModal>
</div>
</div>
</div>
</div>
</template>
Below is my Javascript section with the method that navigates user to next page after login
<script>
import UIUtil from "../../utils/ui-utils";
import ResetPasswordModal from "./ResetPasswordModal";
import $ from "jquery";
import {mAuth} from "../../firebase/firebase-service";
export default {
name: "Login",
components: {ResetPasswordModal},
data() {
return {
email: "",
password: "",
loginDetails: {email: "", password: ""}
};
},
methods: {
async logIn() {
if (this.validateLoginDetails()) {
let response = await mAuth().signInWithEmailAndPassword(this.loginDetails.email, this.loginDetails.password).catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorCode)
console.log(errorMessage)
});
console.log(response.user)
this.$router.push("/jobseeker");
}
},
validateLoginDetails() {
if (!this.validateEmail(this.loginDetails.email)) {
UIUtil.displayAlert("Error", "Wrong email format", "error");
return false;
}
// FIXME: verify login details from server
// verification statement
return true; // success
},
validateEmail(mail) {
// eslint-disable-next-line no-useless-escape
return !!/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(mail);
},
}
}
};
</script>
I only experience this when the navigation happens from a modal component

Laravel (vue and vuex) Adding data always return unautherized

I'm currently making a website that applies Laravel that handles backend, Vuejs that handles frontend and Vuex that handles the CRUD Axios. For my authentication, I didn't use the default that laravel provides instead i use the laravel passport.
I was trying to add data on mysql database but sadly i always receive this error.
message Unauthenticated.
I don't know how to fix the error or pinpoint the root of an error.
Codes
cycle.js (Vuex)
const actions = {
addCycle(context, cycle){
axios.post('/cycle',{
date_loading: cycle.date_loading,
chicken_population: cycle.chicken_population,
clean_up: cycle.clean_up,
date_harvest: cycle.date_harvest,
date_manure_collection: cycle.date_manure_collection,
date_cleaning: cycle.date_cleaning,
date_disinfection: cycle.date_disinfection,
date_rest: cycle.date_rest,
date_next_loading: cycle.date_next_loading,
})
.then(response =>{
context.commit('addCycle',response.data)
})
.catch(error =>{
console.log(error)
})
},
}
ModalAddCycle.vue
<template>
<div
class="modal fade"
id="modalAddCycle"
tabindex="-1"
role="dialog"
aria-labelledby="modalTitle"
aria-hidden="true"
>
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<ValidationObserver v-slot="{ invalid, passes, validate }">
<form #submit.prevent="passes(createCycle)">
<div class="modal-header">
<h5 class="modal-title" id="modalTitle">Add Cycle</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span class="color-close" aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group pl-2 pr-2">
<ValidationProvider
name="loading date"
mode="eager"
v-slot="{ classes, errors }"
>
<label for="date_loading">Loading Date</label>
<div class="row">
<div class="col-9">
<v-date-picker
:class="classes"
v-model="date_loading"
id="date_loading"
title-position="left"
required
/>
</div>
<div class="col ml-4">
<!-- <button class="btn btn-primary" type="button" #click="validate">Check</button> -->
</div>
</div>
<small class="form-text text-error">{{ errors[0] }}</small>
</ValidationProvider>
</div>
<div class="form-group pl-2 pr-2">
<ValidationProvider
name="chicken population"
mode="eager"
rules="numeric"
v-slot="{ classes, errors }"
>
<label for="chicken_population">Chicken Population</label>
<input
:class="classes"
v-model="chicken_population"
id="chicken_population"
type="textr"
class="form-input"
required
/>
<small class="form-text text-error">{{ errors[0] }}</small>
</ValidationProvider>
</div>
<div class="form-group pl-2 pr-2">
<ValidationProvider
name="clean up"
rules="numeric"
mode="eager"
v-slot="{ classes, errors }"
>
<label for="clean_up">Clean up</label>
<input
:class="classes"
v-model="clean_up"
id="clean_up"
type="text"
class="form-input"
required
/>
<small class="form-text text-error">{{ errors[0] }}</small>
</ValidationProvider>
</div>
<div class="form-group pl-2 pr-2">
<label for="date_harvest">Harvest Date</label>
<input
:value="dateHarvest"
id="date_harvest"
readonly
class="form-control-plaintext ml-2"
/>
</div>
<div class="form-group pl-2 pr-2">
<label for="date_manure_collection">Manure Collection Date</label>
<input
:value="dateManureCollection"
id="date_manure_collection"
readonly
class="form-control-plaintext ml-2"
/>
</div>
<div class="form-group pl-2 pr-2">
<label for="date_cleaning">Cleaning Date</label>
<input
:value="dateCleaning"
id="date_cleaning"
readonly
class="form-control-plaintext ml-2"
/>
</div>
<div class="form-group pl-2 pr-2">
<label for="date_disinfection">Disinfection Date</label>
<input
:value="dateDisinfection"
id="date_disinfection"
readonly
class="form-control-plaintext ml-2"
/>
</div>
<div class="form-group pl-2 pr-2">
<label for="date_rest">Rest Date</label>
<input
:value="dateRest"
id="date_disinfection"
readonly
class="form-control-plaintext ml-2"
/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-success">Create</button>
</div>
</form>
</ValidationObserver>
</div>
</div>
</div>
</template>
<script>
import { mapActions } from "vuex";
name: "modalAddCycle";
export default {
data() {
return {
date_loading: new Date(),
chicken_population: "",
clean_up: "",
date_harvest: "",
date_manure_collection: "",
date_cleaning: "",
date_disinfection: "",
date_rest: ""
};
},
methods: {
...mapActions(["addCycle"]),
createCycle() {
this.addCycle({
date_loading: moment(this.date_loading).format("YYYY-MM-DD"),
chicken_population: this.chicken_population,
clean_up: this.clean_up,
date_harvest: moment(this.date_loading).format("YYYY-MM-DD"),
date_manure_collection: moment(this.date_loading).format("YYYY-MM-DD"),
date_cleaning: moment(this.date_loading).format("YYYY-MM-DD"),
date_disinfection: moment(this.date_loading).format("YYYY-MM-DD"),
date_rest: moment(this.date_loading).format("YYYY-MM-DD")
})
.then(response => {
toast.fire({
type: "success",
title: "Create cycle successfully!"
});
console.log()
$("#modalAddCycle").modal("hide");
})
.catch(error => {
swal.fire({
type: "error",
title: "There was something wrong!",
text: error.response.data.message,
showConfirmButton: false,
timer: 3000
});
});
}
},
computed: {
dateHarvest() {
this.date_harvest = moment(this.date_loading)
.add(this.clean_up, "days").format("MM/DD/YYYY");
return this.date_harvest;
},
dateManureCollection() {
this.date_manure_collection = moment(this.date_harvest)
.add(2, "days").format("MM/DD/YYYY")
return this.date_manure_collection;
},
dateCleaning() {
this.date_cleaning = moment(this.date_harvest)
.add(9, "days").format("MM/DD/YYYY")
return this.date_cleaning;
},
dateDisinfection() {
this.date_disinfection = moment(this.date_harvest)
.add(10, "days").format("MM/DD/YYYY")
return this.date_disinfection;
},
dateRest() {
this.date_rest = moment(this.date_harvest)
.add(20, "days").format("MM/DD/YYYY")
return this.date_rest;
}
}
};
</script>
CycleController.php
public function __construct()
{
$this->middleware('auth:api');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
}
public function store(Request $request)
{
// VALIDATION
$this->validate($request, array(
'date_loading' => 'required|date',
'clean_up' => 'required|numeric',
'chicken_population' => 'required|numeric',
));
// STORING CYCLE DATA
$storeCycle = Cycle::create([
'date_loading' => request('date_loading'),
'clean_up' => request('clean_up'),
'chicken_population' => request('chicken_population'),
'date_harvest' => request('date_harvest'),
'date_manure_collection' => request('date_manure_collection'),
'date_cleaning' => request('date_cleaning'),
'date_disinfection' => request('date_disinfection'),
'date_rest' => request('date_rest'),
'date_next_loading' => request('date_next_loading'),
'user_id' => Auth::id()
]);
// GETTING THE CYCLE ID
$cycle = Cycle::where([
['date_loading',$request->get('date_loading')],
['date_harvest',$request->get('date_harvest')],
['user_id' => Auth::id()],
])->first();
//CHECKS IF CYCLE DATA WAS EXISTED
if($cycle){
//STORING CHICKEN POPULATION IN POPULATION TABLE
Population::create([
'chicken_population'=> request('chicken_population'),
'chicken_available'=> request('chicken_population'),
'cycle_id' => $cycle->id ?? 0,
'user_id' => Auth::id()
]);
}
return $storeCycle;
}
api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::apiResources(['cycle' => 'API\CycleController']);
web.php
Route::get('/{any?}', function (){
return view('layout');
})->where('any', '^(?!api\/)[\/\w\.-]*');
You need a passport token for javascript authentication and I quote: All you need to do is add the CreateFreshApiToken middleware to your web middleware group in your app/Http/Kernel.php file:
'web' => [
// Other middleware...
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
For more details check the Laravel documentation from here
Note: Make sure the User model uses Laravel\Passport\HasApiTokens trait
Not sure if your problem is the same but there is a PR in the laravel repo regarding a similar error with API authentication that may help.
https://github.com/laravel/laravel/pull/4764
The original issue and explanation is listed in the description but here's a summary:
OK, I've looked into this and I'm pretty sure it has nothing to do with JSON or the handling of the AuthenticationException, because the AuthenticationException is never even thrown. Try dumping $request->expectsJson() - does this return true? It probably does.
This line is indeed the problem. It's called when the parent tries to construct the Exception:
throw new AuthenticationException(
'Unauthenticated.', $guards, $this->redirectTo($request)
);
But the login route doesn't exist by default, so the route('login') throws an InvalidArgumentException.
This bug is present even in a fresh Laravel install:
laravel new auth-test
cd auth-test
php artisan serve
and then
curl -H "Accept: application/json" http://localhost:8000/api/user
and you will see the same Exception.
This bug seems to have been introduced in laravel/laravel#a14e623.
Workaround: Add a route named "login" or remove the call to route('login') from the Middleware.

Trying to prevent modal close on button click - javascript

I'm working on a small project in ASP.NET MVC, and in one part I need help of javascript.
Acctually there is modal with three inputs, old password, new and confirm new password,
and in case all fields are empty I need to prevent user from closing modal, I tried to solve it like this:
function comparePasswords(currentPassword) {
//Here I will loop throught all of my three inputs to check are they empty
var formInvalid = false;
$('#allInputs input').each(function () {
if ($(this).val() === '') {
formInvalid = true;
}
});
if (formInvalid) {
alert('One or more fields are empty.');
$('#ChangePassword').modal({
backdrop: 'static',
keyboard: false // I need to prevent user from clicking ESC or something
})
}
}
But I get following error (check the image):
EDIT:
FULL CODE:
<div class="form-group">
<label for="UserPassword">Pw:</label>
#Html.TextBoxFor(model => model.PasswordHash, new { #class = "form-control custom-input", data_toggle = "modal", data_target = "#ChangePassword", ariaDescribedby = "basic-addon1" })
</div>
#*Modal for ChangePassword which is opening when user clicks on control above ^*#
<div id="ChangePassword" class="modal fade" role="dialog">
<div class="modal-dialog modal-sm">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Updating password</h4>
</div>
<div class="modal-body" id="allInputs">
#*Modal Old Password*#
<div class="form-group">
<label for="UserPassword">Old password:</label>
<input type="password" class="form-control custom-input modal-trigger" value="Eldin123" name="oldPassword" id="OldPassword" data-toggle="modal">
</div>
#*Modal New Password*#
<div class="form-group">
<label for="UserPassword">New password:</label>
<input type="password" class="form-control custom-input modal-trigger" value="" name="newPassword" id="NewPassword" data-toggle="modal">
</div>
#*Modal Repeat New Password*#
<div class="form-group">
<label for="UserPassword">Confirm new password:</label>
<input type="password" class="form-control custom-input modal-trigger" value="" name="confirmPassword" id="ConfirmNewPassword" data-toggle="modal">
</div>
#*Modal - submit*#
<div class="confirm-login">
<button type="button" class="btn custom-btn-big" onclick="comparePasswords();">NEXT</button>
</div>
</div>
</div>
</div>
</div>#*end of Modal for ChangePassword*#
#*Confirm button*#
<div class="confirm-login">
<button class="btn custom-btn-big" data-target="#">SAVE ALL CHANGES</button>
</div>
</div>
</div>
</div> #*End of User / Administration*#
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script>
function fieldInvalid() {
var formInvalid = false;
$('#allInputs input').each(function () {
if ($(this).val() === '') {
formInvalid = true;
console.log(formInvalid);
}
});
}
function passwordsInvalid() {
var invalidPassword = true;
var oldPw = $("#OldPassword").val();
var newPw = $("#NewPassword").val();
var confirmNewPw = $("#ConfirmNewPassword").val();
if (oldPw != newPw) {
alert('Postojeći password nije ispravan.');
}
else if (oldPw != confirmNewPw) {
alert('Password koji ste unijeli se ne slaže.');
}
else {
invalidPassword = false;
}
return invalidPassword;
}
var comparePasswords = function () {
if (fieldInvalid()) {
alert('One or more fields is empty.');
}
else {
if (!passwordsInvalid()) {
$("#ChangePassword").modal('hide');
}
}
}
</script>
}
So when someone clicks on password input, modal will be opened, and from that modal after informations are there user should click on button "NEXT" and there is event onclick which is calling comparePasswords method.
You are missing bootstrap library file.
Order of the file should be
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
Same Problem (missing bootstrap.js) http://jsfiddle.net/1aeur58f/676/
Problem resolved (by adding bootstrap.js) http://jsfiddle.net/1aeur58f/677/
Hope this will help you.

Activate the button in a form when old values are not equals that new values in ANGULARJS

I am trying to do an edit form in angular. When I am editing the fields in my form they show the old values (typical edit form). The problem is when I try to make disable or enable the submit button form when the new values are totally different from the old values in all fields. The original idea is save changes and do calls to my server if the news values are not equals.
How could I do this in angularJs?
This is my angular controller:
(function () {
'use strict';
app.controller('ProjectController', ProjectController);
ProjectController.$inject = ['$scope', '$http', '$q', 'ProjectService', 'currentUser', '$location'];
function ProjectController($scope, $http, $q, ProjectService, currentUser, $location) {
var vm = this;
vm.init = init;
vm.getProjects = getProjects;
vm.createProject = createProject;
vm.projectToEdit = {
name: '',
version: '',
suffix: '',
description: ''
};
vm.editProject = editProject;
vm.projectToCreate= {
name: '',
version: '',
suffix: '',
description: ''
}
vm.projectFilter = {
name: '',
version: '',
page: 1,
projectId: ''
};
vm.listProject = [];
function init()
{
getProjects();
}
function getProjects()
{
ProjectService.getProjects().then(responseGet);
function responseGet(response)
{
vm.listProject = response.data;
}
}
function editProject(position)
{
vm.projectToEdit = vm.listProject[position];
}
function createProject()
{
ProjectService.createProject(vm.projectToCreate).then(respongeCreateProject);
function responseCreateProject(response)
{
}
}
}
})();
this is my form:
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Edit project</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="ProjectName">Project name</label>
<input class="form-control" ng-model="projCtr.projectToEdit.Name" />
</div>
<div class="form-group">
<label for="Suffix">Suffix</label>
<input class="form-control" ng-model="projCtr.projectToEdit.Suffix" />
</div>
<div class="form-group">
<label for="Version">Version</label>
<input class="form-control" ng-model="projCtr.projectToEdit.Version" />
</div>
<div class="form-group">
<label for="Description">Description</label>
<input class="form-control" ng-model="projCtr.projectToEdit.Description" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Right now my flow assigns in a new value the fields to edit, called vm.projectToEdit. In the function editProject(position) I get the array position where is my object to edit.
Kind regards

Categories

Resources