Prime-NG Confirm Dialog: Hide the Button after Confirmation - javascript

I'm struggling with a problem using Angular and PrimeNG.
There is an Input Field for weight allowing numbers up to 150. If the typed in value is greater than 150, a Confirm Button appears below the Input Field.
If this button is clicked, the Confirm Dialog pops up, asking "Are you sure?". It contains two buttons to choose from, "Yes" and "No".
1.) Choosing "No" should close the Confirm Dialog and delete the previously typed-in value in the input field (this works). The Confirm Button shall vanish (fails).
2.) Choosing "Yes" should close the Confirm Dialog and leave the typed-in value (this works). Confirm button shall vanish (also fails).
Is it somehow possible to let the button disappear after the Confirm Dialog is closed?
test.component.html:
<div class="p-col-12 p-md-6 p-lg-5">
Weight:
<div class="ui-inputgroup">
<input pInputText type="number" id="weight" name="weight" [(ngModel)]="newTest.testWeight"
placeholder="---">
<span class="ui-inputgroup-addon">kg</span>
</div>
<div *ngIf="validateIfWeightOutsideRange()">
<div>
<p-confirmDialog key="confirmWeightTest"></p-confirmDialog>
<button type="button" (click)="confirmWeightTest()" pButton icon="pi pi-check"
label="Please confirm!">
</button>
<p-messages [value]="messagesWeightTest"></p-messages>
</div>
</div>
</div>
test.component.ts
messagesWeightTest: Message[] = [];
confirmWeightTest() {
this.confirmationService.confirm({
message: 'Are you sure?',
header: 'Confirmation',
icon: 'pi pi-exclamation-triangle',
key: 'confirmWeightTest',
accept: () => {
this.messagesWeightTest = [{
severity: 'info', summary: 'Confirmed', detail: 'The input is correct.'}];
},
reject: () => {
this.sessionService.newTest.testWeight = null;
}
});
}
Please note: The method "validateIfWeightOutsideRange()" works, therefore I think it's unnecessary to show it here.
Here is the link to PrimeNG's documentation: https://www.primefaces.org/primeng/#/confirmdialog
Maybe you have an idea?

You can simply take one bool variable and set it on confirmDialog button click
messagesWeightTest: Message[] = [];
public weightConfirmed: boolean = false;
confirmWeightTest() {
this.confirmationService.confirm({
message: 'Are you sure?',
header: 'Confirmation',
icon: 'pi pi-exclamation-triangle',
key: 'confirmWeightTest',
accept: () => {
this.messagesWeightTest = [{
severity: 'info', summary: 'Confirmed', detail: 'The input is correct.'}];
this.weightConfirmed = true;
},
reject: () => {
this.sessionService.newTest.testWeight = null;
this.weightConfirmed = true;
}
});
}
<div *ngIf="validateIfWeightOutsideRange()">
<div>
<p-confirmDialog key="confirmWeightTest"></p-confirmDialog>
<button *ngIf="!weightConfirmed" type="button" (click)="confirmWeightTest()" pButton icon="pi pi-check"
label="Please confirm!">
</button>
<p-messages [value]="messagesWeightTest"></p-messages>
</div>
</div>

Related

How to pass a variable from one method to another Vue?

Below is an example of my old code which was working. This code created a confirmation screen and on conformation deleted a user. However I want to use a toast element to help create a better confirmation screen. This toast element requires the methods to be split up into onConfirm and onReject. And im wondering if there is a way to pass the variable from my deleteUser method into the onConfirm method similar to how I pass it in the code below. (.then(this.onTeacherDeleted(user))
deleteUser(user) {
if (confirm("Are you sure you want to delete: " + user.name + "?")) {
this.working = true;
axios.delete('/teachers/' + user.id)
.then(this.onTeacherDeleted(user))}
// this.$toast.add({severity: 'warn', summary: 'Are you sure?', detail: 'Are you sure you want to delete this placement?', group: 'bc'});
},
onTeacherDeleted (user) {
this.$toast.add({severity:'success', summary: user.name + 'Deleted Successfully', detail:'The teacher was successfully delted from the database', life: 3000});
window.location.reload()
}
How do I pass the user variable into the onConfirm method from the deleteUser method?
deleteUser(user) {
this.$toast.add({severity: 'warn', summary: 'Are you sure?', detail: 'Are you sure you want to delete this placement?', group: 'bc'});
},
onConfirm(user) {
this.$toast.removeGroup('bc');
this.working = true;
axios.delete('/teachers/' + user.id)
.then(this.onTeacherDeleted(user))
},
onReject() {
this.$toast.removeGroup('bc');
},
The onConfirm and onReject are both on click events that happen earlier in the code (see below) :
<button class="btn border border-success rounded-3" type="button" #click="onConfirm" this.onTeacherDeleted(user) aria-expanded="false">
<button class="btn border border-danger rounded-3" type="button" #click="onReject" aria-expanded="false">
If you show more of your code maybe i can give a better solution, but from what i can see, you can just make a variable to track which user is being deleted at the moment and set its value in the:
deleteUser(user) {
this.$toast.add({severity: 'warn', summary: 'Are you sure?', detail: 'Are you sure you want to delete this placement?', group: 'bc'});
this.userToBeDeleted = user;
},
And then just use that variable in the onConfirm:
onConfirm() {
this.$toast.removeGroup('bc');
this.working = true;
axios.delete('/teachers/' + this.userToBeDeleted.id)
.then(this.onTeacherDeleted(this.userToBeDeleted))
},

Bootstrap V5 Form Validation & Sweetalert2 : Showing success message after successful submission

I have simple form based on Bootstrap 5 with a validation option I'm trying to display alert message if the form field is successfuly submited using Sweatalert2.
Here is my Code :
HTML
<form action="" method="POST" class="needs-validation" novalidate>
<label for="validationCustomUsername" class="form-label">Username</label>
<div class="input-group has-validation mb-3">
<span class="input-group-text" id="inputGroupPrepend">#</span>
<input type="text" class="form-control" id="validationCustomUsername" placeholder="Username *" aria-describedby="inputGroupPrepend" required />
<div class="invalid-feedback">
Please choose a username.
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form</button>
</form>
JS
(function () {
'use strict'
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.querySelectorAll('.needs-validation')
// Loop over them and prevent submission
Array.prototype.slice.call(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})()
Live Example
I was having the same issue and came across this post which quite helpful.
Below code might help:
......
form.classList.add('was-validated');
if (form.reportValidity()) {
event.preventDefault()
Swal.fire({
position: 'center',
icon: 'success',
title: 'Your application has been submitted successfully!',
showConfirmButton: false,
timer: 2500
}).then((result) => {
// Reload the Page
location.reload();
});
}
It will reload the page after form submission.
This is may be too late, but I hope it can help others. I have the same issue. Then, I tried to combine bootstrap validation inside the SweetAlert Confirmation Box before submitting the form.
I create the code like below:
$('#submitForm').on('click', function (e) {
e.preventDefault();// prevent form submit
/*this part is taken from bootstrap validation*/
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function (form) {
if (form.checkValidity() === false) {
form.classList.add('was-validated');
}
else {
Swal.fire({
title: 'Are you sure?',
text: "It cannot be undone",
type: 'warning',
icon: 'question',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, send it!'
}).then((result) => {
if (result.value) {
/*submit the form*/
$("#formsubmitsekali").submit();
}
});
}
}, false);
});
submitForm is the ID name for the button ID for submit the form.
formsubmitsekali is the form ID.
By doing so, if the required field is not filled, it will show the bootstrap validation without showing Sweetalert confirmation box. But if all of required fields are filled, the Sweetalert will show up.
The same behavior also happens if you have email input type, but it is filled by non-email, it will run the bootstrap validation first. It is also work if you use HTML5 pattern inside the input type and the user fills with the wrong pattern.

How to add new elements to an objects-array using event listener and show it on the html page

I was trying to make a todo application, then I wanted to add new todo using a form and an event listener but, when I finished the code the app only adds the written text to the object-array and doesn't actually add it to the todos list in the html page.
I'll provide a small code down below showing the array, the setup code and the html as well in order to make this question short, but if you want to see the whole application code feel free to check this github's repository: https://github.com/salahmak/Todo-application
You can also check out the live version of the app from this ngrok link (i'll keep it live until I fix the problem) : http://7eb95c9a.ngrok.io
The code:
// The array
const todos = [{
text: 'wake up',
completed: true
}, {
text: 'get some food',
completed: true
}, {
text: 'play csgo',
completed: false
}, {
text: 'play minecraft',
completed: true
}, {
text: 'learn javascript',
completed: false
}];
//creating p elements and assigning their text content to each "text" property of the "todos" array
todos.forEach(function(todo) {
let p = document.createElement('p');
p.textContent = todo.text;
document.querySelector('#todo').appendChild(p);
})
<h1>Todos</h1>
<form id="form">
Add a new todo
<input type="text" placeholder="Type your first name" name="firstName">
<button>Submit</button>
</form>
document.querySelector('#todo').appendChild(p); You're appending to a non-existent #todo element. Throw in a <div id="todo"></div> and it'll work.
Working:
// The array
const todos = [{
text: 'wake up',
completed: true
}, {
text: 'get some food',
completed: true
}, {
text: 'play csgo',
completed: false
}, {
text: 'play minecraft',
completed: true
}, {
text: 'learn javascript',
completed: false
}];
//creating p elements and assigning their text content to each "text" property of the "todos" array
todos.forEach(function(todo){
let p = document.createElement('p');
p.textContent = todo.text;
document.querySelector('#todo').appendChild(p);
})
<body>
<h1>Todos</h1>
<form id="form">
Add a new todo
<input type="text" placeholder="Type your first name" name="firstName">
<button>Submit</button>
</form>
<div id="todo"></div>
<script src="todo-app.js"></script>
</body>
The main issue here is that the #todos element is not present in your HTML, which means there is no "destination" for todos data to be displayed in your page.
As an improvment to your app, consider defining a reusuable function like updateView() that updates the contents of the #todo element to display the current data in the todos array. In you app, that could be called:
after submission of your form, to display newly added todos
on load, to display inital data
One way to implement this is as follows:
// The array
const todos = [{
text: 'wake up',
completed: true
}, {
text: 'get some food',
completed: true
}, {
text: 'play csgo',
completed: false
}, {
text: 'play minecraft',
completed: true
}, {
text: 'learn javascript',
completed: false
}];
/* Reusable function that updates the view container with current
data in todos array */
function updateView() {
const container = document.getElementById("todo");
/* Clear list */
container.innerHTML = "";
/* Populate list with current todos data */
todos.forEach(function(todo) {
const p = document.createElement('p');
p.textContent = todo.text;
container.appendChild(p);
});
}
const form = document.getElementById("form");
/* Add form submit event handler to add actual todo to list(s) */
form.addEventListener("submit", function(event) {
/* Prevent default "page reload" form submit behavior */
event.preventDefault();
/* Extract text from input field */
const text = form.querySelector('input[name="firstName"]').value;
/* Add new todo item to todos array (model) */
todos.push({
text: text,
completed: false
});
/* Update container with added todo data */
updateView();
});
/* Populate container with inital data */
updateView();
<h1>Todos</h1>
<form id="form">
Add a new todo
<input type="text" placeholder="Type your first name" name="firstName">
<button>Submit</button>
</form>
<!-- Add a DOM element that contains the actual display list -->
<div id="todo">
</div>

Javascript unobtrusive onclick with sweetalert

Good Evening,
I'm fairly new to JavaScript. I have a book and scour the internet when looking for answers. I see that the JavaScript landscape seems to have a plethora of paths and frameworks. To the question, I'm trying to use unobtrusive javascript with sweetalert. I had an issue with onclick finishing the function before an option was selected. I altered the function to return false by default and let the path nullify the onlick function and click the button. Is the following reasonable form ? Or would another method be recommended for the same effect? If so, please indicate why its better. Also, no framework/library answers for the moment please.
window.onload = function() {
function doSomething() {
var button = document.getElementById("edit");
swal({
title: 'Are you sure?',
text: 'You will not be able to recover this imaginary file!',
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes, Update it!',
cancelButtonText: 'No, stop'
}).then((result) => {
if (result.value) {
button.onclick = null;
button.click();
// For more information about handling dismissals please visit
// https://sweetalert2.github.io/#handling-dismissals
} else if (result.dismiss === swal.DismissReason.cancel) {
swal(
'Cancelled',
'No Update Occured :)',
'error'
)
}
})
return false;
}
document.getElementById("edit").onclick = doSomething;
<form action="{{route('categories.update',$cat->id)}}" method="post">
{{method_field('patch')}}
<div class="form-group">
<label for="title">Name</label>
<input type="text" name="name" class="form-control" value="{{$cat->name}}">
<label for="description">Description</label>
<input type="text" name="description" class="form-control" value="{{$cat->description}}">
</div>
<button class="btn btn-primary" type="submit" id="edit">Edit Category</button>
{{#csrf_field()}}
</form>

Save Alert text input into database from ionic alert

I have created an ionic alert to decline a request. I want the user to input a reason for declining the request before they hit confirm. I then would like to save this data into my database and have a method (declineRequest) setup to do so.
The method is working for declining the request. The issue is how to save the alert 'Notes' input field into the database, and how to make sure the declineRequest method is only run when 'confirm' is clicked.
Here is the code:
The HTML:
<ion-list>
<ion-card *ngFor="let r of requests; let i = index">
<ion-item>
<h2>{{r.userId}}</h2>
<p>{{r.requestDetail}}</p>
<p>{{r.fromDateTime}} to {{r.toDateTime}}</p>
<p>{{r.type}}</p>
</ion-item>
<ion-card-content>
<button class="approve" ion-button icon-left color="secondary" (click)="approveAlert(r.id)">
<ion-icon name="checkmark"></ion-icon>
Approve
</button>
<button class="decline" ion-button icon-left color="danger" (click)="declineAlert(r.id)">
<ion-icon name="close"></ion-icon>
Decline
</button>
</ion-card-content>
</ion-card>
</ion-list>
The TS:
declineAlert(requestId) {
const alert = this.alertCtrl.create({
title: 'Confirm Request Declined',
subTitle: 'Notes:',
inputs: [
{
name: "Note",
type: "text",
placeholder: 'Please enter reasons'
}],
buttons: [ { text:"Cancel"
},
{ text: "Confirm",
handler: data => {
console.log(JSON.stringify(data));
console.log(data.Note);
}
}],
cssClass: 'alertCustomCss'
});
alert.present();
console.log(requestId);
let notes = Note;
this.declineRequest(requestId, notes);
}
I have tried different methods but cannot seem to get the text from the decline 'notes' to save.
Any help would be greatly appreciated.
As Keval pointed out you just need to use your method inside the handler like so:
declineAlert(requestId) {
const alert = this.alertCtrl.create({
title: 'Confirm Request Declined',
subTitle: 'Notes:',
inputs: [
{
name: "Note",
type: "text",
placeholder: 'Please enter reasons'
}],
buttons: [ { text:"Cancel"
},
{ text: "Confirm",
handler: data => {
this.declineRequest(requestId, data.Note);
// additional steps like pop() page etc
}
}],
cssClass: 'alertCustomCss'
});
alert.present();
}
Try with my working code
let alert = this.alertCtrl.create({
title: 'Confirm Request Declined',
inputs: [
{
type: 'textarea',
name: 'Message',
placeholder: 'Please enter reasons',
},
],
buttons: [
{
text: 'Yes',
handler: data => {
var message = data.Message;
//Here is Api call
}
},
{
text: 'No',
role: 'cancel',
handler: data => {
var message = data.Message;
//Your logic
}
}
]
});
alert.present();

Categories

Resources