How to change an Alert to a Modal using SweetAlert2 - javascript

I am trying to change an Alert to a Modal, I have a function in Typescript to subscribe an user for example when the subscriber is ok, I can call a Modal of success, but I have another alert in this function if the subscribe not works, my question is, how can I change the second alert (which does not work the subscribe) from my function to a Modal of error? I mean, I want to put two different Modals for the same function.
I've tried to make a function in JavaScript, using Sweetalert2 and using with Angular, but both it didn't work, also something like this:
<swal #ok
type="success"
title="Cadastro realizado comsucesso!" (confirm)="CadastrarUsuario()">
</swal>
<swal #ok
type="error"
title="Cadastro não realizado!" (confirm)="CadastrarUsuario()">
</swal>
<button type="submit" [swal]="ok" class="btn btn-primary def-button">Cadastrar Usuário</button>
This is my function:
cadastro-user.component.ts
CadastrarUsuario() {
if (this.roleVisivel == 1) {
this.lider.perfil = "LiderTecnico";
this.funcionarioService.cadastrarFuncionarioPorAdmin(this.lider).subscribe (
data => {
// alert("CADASTRADO COM SUCESSO !")
location.reload();
},
error => {
alert("Algo de errado nao esta certo.")
}
);
} else if (this.roleVisivel == 2) {
this.user.admin = true;
this.usuariosService.cadastrarGerente(this.user).subscribe (
data => {
// alert("CADASTRADO COM SUCESSO !")
location.reload();
},
error => {
alert("Algo de errado nao esta certo.")
}
);
}
}
cadastro-user.component.html
<swal #ok
type="success"
title="Cadastro realizado comsucesso!" (confirm)="CadastrarUsuario()">
</swal>
<button type="submit" [swal]="ok" class="btn btn-primary def-button">Cadastrar Usuário</button>

Related

Hi! When adding localstorage items on my site, after refreshing the page the message keeps appearing and so on, what can I do in this case?

I'm adding localstorage items on the websites of the companies I work for, and I've come across a problem on some websites; when adding the item to storage, it is displayed normally on the site, but when accepting and refreshing the page the message continues to appear, what could be causing this?
I checked that maybe it could be the version of JQuery I'm using (JQuery 1.7), but I updated the library and the error persists, can anyone help me?
JS Code:
function cookies(functions) {
const container = document.querySelector('.cookies-container');
const save = document.querySelector('.cookies-save');
if (!container || !save) return null;
const localPref = JSON.parse(window.localStorage.getItem('cookies-pref'));
if (localPref) activateFunctions(localPref);
function getFormPref() {
return [...document.querySelectorAll('[data-function]')]
.filter((el) => el.checked)
.map((el) => el.getAttribute('data-function'));
}
function activateFunctions(pref) {
pref.forEach((f) => functions[f]());
container.style.display = 'none';
window.localStorage.setItem('cookies-pref', JSON.stringify(pref));
}
function handleSave() {
const pref = getFormPref();
activateFunctions(pref);
}
save.addEventListener('click', handleSave);
}
function marketing() {
console.log('Função de marketing');
}
function analytics() {
console.log('Função de analytics');
}
cookies({
marketing,
analytics,
});
function fechar() {
document.getElementById('cookie').style.display = 'none';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
PHP Code:
<div class="cookies-container" id="cookie">
<div class="cookies-content">
<div>
<p>
Este site ultiliza cookies e outras tecnologias semelhantes para
melhorar a sua experiência em nossa plataforma. Você aceita
a politica de privacidade?
</div>
<div class="cookies-pref">
<button class="cookies-save btn btn-warning">Sim</button>
<button onclick="fechar()" class="btn btn-light cookies-no" style="color: #000;">Não</button>
</div>
<div class="politica">
Ver nossa política de privacidade?
</div>
</div>
</div>
<!-- <?= $CAMINHO ?>/index.php?sessao=<?= verifica($sequencia . $politicaPrivacidade . $complemento); ?>&id=<?= $menuNossaCidade['id'] ?> -->
(I'm using jquery 1.7)

How can I know the value of a checkBox marked with vueJS

I am finishing a project with Laravel and vueJS, but I have a problem. In a modal, I select a checkbox (there may be several or not) and that value of the marked checkbox, I need to keep it for when I press a button in another modal, the value of the checkbox is sent to the controller to make an update. It does well for me with the first check, but if I select another, the first one always takes me. I'm trying to catch it by class, but nothing, always take first.
I attach my current code:
<div class="modal-body">
<div v-if="bonosUsuarioSolicitante.length == 0">No hay bonos disponibles</div>
<div v-for="data in bonosUsuarioSolicitante" class="ml-5">
<label class="form-check-label">Tiempo Restante</label>
<input type="checkbox" class="form-check-input ml-3 codContrato" :value="data.codContrato" #click="iniciarActuacion">
<label class="form-check-label ml-5">{{data["tiempoRestanteBono"]}} Min</label>
</div>
</div>
There I put the values ​​of the checkbox inside the modal that calls the "startAction" function until there well. If all goes well, this modal is closed.
In another modal, I have this:
<button type="button" class="btn btn-primary" #click="detenerActuacion">Detener Actuacion</button>
and this function is the one that I would update
detenerActuacion: function(){
clearInterval(cronometro);
let minutosContratados = $("#tiempoContratado").val();
// Mínimo se va a restar 5 minutos a la actuación una vez iniciada.
let minutosActuacion = 5
let minutosEmpleados = document.getElementById("minutos").innerText;
if(minutosEmpleados < minutosActuacion){
minutosEmpleados = minutosActuacion;
}
// variables que van al controlador
let tiempoEmpleadoCalculado = minutosContratados - minutosEmpleados;
let mensaje = $("#mensajeActuacion").val();
let codV3 = $("#codV3").val();
let codContrato = $(".codContrato").val();
let url = "/actualizarTiempo";
axios
.post(url, {
tiempoEmpleado: minutosEmpleados,
tiempoRestante: tiempoEmpleadoCalculado,
mensajeActuacion: mensaje,
codContrato: codContrato,
codV3: codV3,
}
)
.then((response) => {
$("#actuacionCorrecta").text("Actuación guardada con exito y tiempo del bono actualizado")
})
.catch(
(error) => $("#actuacionError").append(error)
);
},
I have jQuery mixed and that it should not be done together with vueJS. In the first modal it is where I could get the codContrato which is what I need to update. Hence I try to capture it with class. As I say, the first one goes well ... But that's it.
Use v-model, it could be very easy.
Check the following example code:
<template>
<div class="container">
<div v-for="(data,index) in check_data" :key="index">
<input type="checkbox" :value="data.id" #change="check()" v-model="checked">test {{data.value}}
</div>
</div>
</template>
<script>
export default {
name: "example",
data(){
return {
check_data:[{id:1,value:'a'},{id:2,value:'b'},{id:3,value:'c'}],
checked:[],
}
},
methods:{
check(){
console.log(this.checked);
},
}
}
</script>

Sweet alert doesn't send the Id of my element when submiting the form (ASP.Net core mvc)

I have a question regarding the use of sweet alert on Asp.net core 2.2 mvc. While trying to make an alert to confirm a post event on my controller AdminUsersController, the action returns an error because the requested id is null, but when I don't use sweet alert the event works perfect.
I'm trying to get this to work on Asp.net core 2.2 on Visual studio 2017 community, I've never had any problems before with crud operations regarding Id's. I'm trying to make it work on a table with many results with diffrent Ids.
like so : https://gyazo.com/9366bab83fa4401e1b88b28e27ffa55f
Controller Index Post
//== Action - Index
[Authorize(Roles = SD.Tier3User)]
[HttpPost, ValidateAntiForgeryToken]
public async Task<ActionResult> Index(string id)
{
var UserFromDb = await _db.ApplicationUser.FindAsync(id);
if (UserFromDb.LockoutEnabled == true)
{
//== Lo desactiva (LockOutEnabled = 0)
UserFromDb.LockoutEnabled = false;
}
else
{
//== Lo activa (LockOutEnabled = 1)
UserFromDb.LockoutEnabled = true;
}
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
HTML button
<td>
#if (User.IsInRole(SD.Tier3User))
{
<a asp-action="Edit" asp-route-id="#item.User.Id" class="btn btn-sm
btn-outline-primary">Editar</a>
== HERE I USE SWEET ALERT ===
#if (item.User.LockoutEnabled)
{
<button type="submit" onclick="CambiarEstado()" asp-route-id="#item.User.Id" class="btn btn-sm btn-outline-warning">Desactivar</button>
}
else
{
<button type="submit" onclick="CambiarEstado()" asp-route-id="#item.User.Id" class="btn btn-sm btn-outline-success">Re-activar</button>
}<a asp-action="Delete" asp-route-id="#item.User.Id" class="btn btn-sm btn-outline-danger"><i class="far fa-trash-alt"></i></a>
}
</td>
JS Sweet alert
<script>
function CambiarEstado() {
document.querySelector('#Estado').addEventListener('submit', function (event) {
var form = this;
event.preventDefault();
swal({
title: "¿Desea cambiar el estado de este usuario?",
icon: "success",
buttons: [
'No',
'Si'
],
}).then(function (isConfirm) {
if (isConfirm) {
swal("¡Estado cambiado!", {
buttons: false,
timer: 500,
}).then(function () {
form.submit();
});
} else {
swal("Acción cancelada", "Recuerde que un usuario desactivado no puede entrar al sistema", "error");
}
})
});
}
</script>
It was suppose to de-activate the user, but first ask if I'm sure of that action, Instead it returns an error since the id the post event got was null.
Thanks in advance!
The asp-route-* attribute is not valid on a button element. That attribute is specifically utilized by the AnchorTagHelper (i.e. for a elements). You need to either use an actual anchor tag, and simply style it as a button:
<a onclick="CambiarEstado()" asp-action="Foo" asp-route-id="#item.User.Id" class="btn btn-sm btn-outline-warning">Desactivar</a>
Or you'll need to create a hidden input within your form tag to hold the id:
<input type="hidden" name="id" value="#item.User.Id" />
Note: it's unclear what's actually happening here, so you should bear in mind that if you use the action link approach, that will not submit anything. It's a regular GET request at that point, and the id will be added as query param to the href that's generated (hence the need to also specify asp-action). More likely than not, you want to stick with the button and add a hidden input.

Confirm before delete in Sails.js

I'm currently editing a back-end page, but I have a few problems.
I need a confirmation before I delete the Action as you can see I tried this so far but my code is completely skipping the confirm() and only redirects to the index.
Please take a look at the controller code below
delete(req, res, next) {
Action
.findOne(req.param('id'))
.then(({id}) => {
confirm('U staat op het punt een actie te verwijderen, klik op "ok" om hier mee door te gaan');
if(confirm()=== true) {
Action
.destroy(id)
.then(() => {
FlashService.setFlash(req, 'success', 'Action has been deleted')
res.redirect('/answer/index')
})
.catch(err => res.redirect('/answer/index'))
}
})
.catch(err => res.redirect('/answer/index'))
}
}
I also tried console.log to see where my code is stranding but that would only give this error:
Unhandled rejection ReferenceError: confirm is not defined
edit
I tought it also might be usefull to maybe see the HTML so here you go
as you can see the delete is called upon submit maybe I'm doing that extremly wrong but it seems to work besides the confirm mentioned before
<form action="/action/delete/<%= action.id %>" method="POST">
<button type="submit"
class="btn btn-sm btn-icon btn-pure btn-default on-default"
data-toggle="tooltip"
data-original-title="Verwijder"><i class="icon wb-trash" aria-hidden="true"></i>
</button>
</form>
EDIT 2.0
I kind of fixed the problem but still not really I made the following javascript for the delete it's a little basic but that isn't the problem please take a look
<script>
function Delete(){
let c = confirm('U staat op het punt een actie te verwijderen, klik op "ok" om hier mee door te gaan');
if (c){
console.log("done");
window.location.href = "/action/delete/<%= action.id %>"
}
else{
console.log("failed")
window.location.href = "/answer/show/<%= answer.id %>"
}
}
</script>
however, when I go to this page it says "action not defined" but I'm quite sure it is defined to be honest.
I don't really know what I'm doing wrong, any help would be nice
You cannot use the client side confirm javascript on the server side. It does not exist. You should instead call confirm before sending request to the server.
Like so
<button onclick="delete()">Delete</button>
<script>
function delete() {
var confirm = confirm("Do you want to delete?")
if(confirm){
// Call server
}
}
</script>

"Twitter like" follow button

I want to create an like button like twitter, i used from this code:
$(document).ready(function(){
$('.btn-follow').on('mouseover', function(e){
if ($(this).hasClass('following')){
$(this).removeClass('btn-primary').addClass('btn-danger').text('UnFollow');
}
})
$('.btn-follow').on('mouseleave',function(e){
if ($(this).hasClass('following')){
$(this).text('Following').removeClass('btn-danger').addClass('btn-primary');
}
})
$('.btn-follow').on('click',function(e){
$(this).toggleClass('following follow')
if ($(this).hasClass('follow')){
alert('unfollow')
$(this).text('Follow').removeClass('btn-danger')
}else{
alert('follow')
$(this).text('Following')
}
})
});
and in html i have this:
<button class="btn btn-primary btn-follow following">Following</button>
<br />
<br />
<button class="btn btn-follow follow">Follow</button>
but i think it 's very dirty code and have some bugs. How i can fix this code?
Ok the main problem was css specificity not letting btn-danger class take any effect over btn-success.
So as a solution i used an empty class that i made up. To track if the button is being followed or not.
Whenever i added btn-success i added following class. And through class, as you did, i was able to track the state of the button.
With bootstrap!!!
http://jsfiddle.net/vjZRA/1/
Without bootstrap:http://jsfiddle.net/vjZRA/
Code Below:
var btn = $('.btn');
btn.click(h);
btn.hover(hin, hout);
function hin() {
if (btn.hasClass('follow')) {
btn.text('Stop Following');
btn.removeClass('btn-success');
btn.addClass('btn-danger');
} else {
btn.addClass('btn-primary');
}
}
function hout() {
if (btn.hasClass('follow')) {
btn.text('Following');
btn.removeClass('btn-danger');
btn.addClass('btn-success follow');
}
btn.removeClass('btn-primary');
}
function h() {
if (btn.hasClass('follow')) {
btn.removeClass('btn-success follow');
btn.text('Follow');
btn.removeClass('btn-danger');
} else {
btn.text('Following');
btn.addClass('btn-success follow');
}
}
and then add css in style tag or wherever you want
.follow{}

Categories

Resources