Repetitive javascript cycle - javascript

good night, I have this view (the image) which is part of an invoice, this is precisely the detail of the invoice, and I have in this detail a javascript function so that while I write the name of the product I look for the product in the database and when I select it I fill the input of the unit price corresponding to that product, until there all wonders, but the problem is that by pressing the + button to enter a new line and load a new product the function javascript no longer works, it occurred to me that I can use a foreach or something similar to make that function work every time a new line is inserted but I can not make it work, I leave the code:
//search in the database
$("#inputPrecioProducto").devbridgeAutocomplete({
showNoSuggestionNotice: true,
serviceUrl: '/maderas/facturar/leer_productos',
noSuggestionNotice: 'No se encontraron datos',
onSelect: function (suggestion) {
$('#inputIdProducto').val(suggestion.data)
$('#inputPrecioUnidad').val(suggestion.precio_unidad);
}
});}
// Product Field Repeater
$('.repeater').repeater({
hide: function (deleteElement) {
var elemento=$(this);
swal({
title: "Estas Seguro?",
text: "Se borrará toda la fila!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Si, bórralo!",
cancelButtonText: 'Cancelar',
closeOnConfirm: false
}, function(){
swal("Producto Borrado!", "Se ha eliminado el Producto.", "success");
elemento.remove();
sumarTotales();
crearIgv();
});
},
isFirstItemUndeletable: true
});
// ./ Product Field Repeater

Related

trying to use sweetalert for confirmation [duplicate]

This question already has answers here:
How to have sweetalert return true/false for confirm without promise?
(4 answers)
Closed last month.
Here is my code where i am using sweetalert latest code for showing up a confirmation just like a javascript confirm box to act if ok, is pressed adn if its a cancel, do nothing,
Here is my try and my original code
var rtrnval = swal({
title: "Check!",
text: "You must select a task before entering hours.",
type: "warning",
showCancelButton: true,
confirmButtonColor: "##DD6B55",
confirmButtonText: "Confirm",
closeOnConfirm: false
}, function(isConfirm){
return isConfirm; //Will be either true or false
});
alert(rtrnval); return;
my original code is like this
var rtrnval = confirm("You must select a task before entering hours.");
it is not showing the sweetalert box when i change confirm to swal, it throws error on the function but when i use confirm, the function works properly,
i am unable to read the value being returned to me like true/false so i ca act upon it
any guidance, greatly appreciated
i already posted code what i tried
here is what i want to replace
function ConfirmDelete(id){
var rtrnval = confirm("are you sure!!");
if (rtrnval == 1)
{
location='page2.php='+id
}
return 0
}
and some cases i am doing this
return confirm("are you sure")
Try this:
Swal.fire({
title: "Check!",
text: "You must select a task before entering hours.",
type: "warning",
showCancelButton: true,
confirmButtonColor: "##DD6B55",
confirmButtonText: "Confirm",
closeOnConfirm: false
}).then((result) => {
if (result.isConfirmed) {
console.log('Confirmed');
} else if (result.isDenied) {
console.log('Canceled');
}
})

Jquery repeater delete item not updating values

I am using this jquery repeater.
I am using custom calculations on each addition of form, say multiplying one input with another, and then making a total of multiplication results.
Problem is when we click on delete, it just hides the row but don't delete values of the item,
When we delete one more item, then it will delete the first item which was hidden and my calculation is get updated.
I check the number of class on delete of item, it does not reduce on first delete, it always reduces on the second delete,
How to completely delete the row with its values?
var _CalTotal = function () {
console.log($(".billitem_quantity").length );
//Calculate total of quantity
var total_quantity = 0;
$(".billitem_quantity").each(function(){
total_quantity += parseFloat($(this).val());
});
$('#itemquantity_total').val(total_quantity.toFixed(2));
**//Calculate total of amount**
var total_amount = 0;
$(".billitem_total").each(function(){
total_amount += parseFloat($(this).val());
});
$('#bill_total').val(total_amount.toFixed(2));
console.log('test');
}
Below is code for hide,
hide: function(deleteElement) {
Swal.fire({
title: "Are you sure to cancel this order?",
text: "You will not able to revert this",
icon: "question",
showCancelButton: true,
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, revert it!",
reverseButtons: true,
}).then(function(result) {
if (result.value) {
$(this).slideUp(deleteElement);
//I guess something is missing here to delete that item with first delete fire.
_CalTotal(); //Here i am calling calltotal function.
} else if (result.dismiss === "cancel") {
}
});
},
After some debugging I found that setting a setTimeout() of 1 second removed your issue. This means some code is asynchronously processed in the background. Therefore you need a callback function or a promise.
You can do it like this by adding to the slideUp() callback function:
hide: function(deleteElement) {
Swal.fire({
title: "Are you sure to cancel this order?",
text: "You will not able to revert this",
icon: "question",
showCancelButton: true,
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, revert it!",
reverseButtons: true,
}).then(function(result) {
if (result.value) {
$(this).slideUp(function(){
deleteElement();
_CalTotal();
);
} else if (result.dismiss === "cancel") {
}
});
},
I got the solution from this question (not the accepted answer).

Error when moving an item in a drag and drop list

I am working on a drag and drop list, I need that every time you try to move an item on the list ask if you really want to move it, if so, make the move, if not, return it to its initial position.
function handleDragEnd(e) {
swal({
title: "Are you sure?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#f8c286",
confirmButtonText: "Accept",
cancelButtonText: "Cancel",
html: true
},
function(isConfirm){
if (isConfirm) {
e.target.classList.remove('over');
var start = $("#"+e.target.id).prev().attr('id');
var end = $("#"+e.target.id).next().attr('id');
Calculate(start,e.target.id,end,data);
swal("Successfull","change made", "success");
} else {
this.ondragexit;
}
});
But I have errors in both cases, when it's affirmative, I get error in the remove
And when I don't want to move it, he lets me do it anyway.
How can it be corrected to work properly?
Could you help me, please?

SweetAlert2: Really no way to stop JS code until a button is clicked?

In the Swal Github is advised to ask questions to SweetAlert2 in SO, therefore my posting here...
Behind a save button in my (asp.net core) app, I check some things and - in some cases - have to ask the user (yes/no) and - depending on his selection - have to overwrite some data before store.
If I use an (jQuery) alert or a confirm, the code stops, until the user has clicked a button.
In Swal, I don’t have found any way (including “.then(“) to stop the code, until the user has clicked a button.
The message is shown, but the code runs further....
Is it really not possible to stop the code with Swal...?
=> If there is a way, how to do...?
Thanks
It supports callback right? Here is some code which I found in the examples.
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
allowOutsideClick: false,
allowEscapeKey: false,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.value) {
Swal.fire(
'Deleted!',
'Your file has been deleted.',
'success'
)
}
})
You can continue the execution based on the result.value
It seems, as there is really now way to stop the JS code until the user has done his chosen
So.. I had to change my logic.
Logic before:
To check something ( 1 ) , show an swal (e.g. set focus to a control) and then return in code works (of cause of the return).
This way,the message is showed (until the user close it) and the data are not stored.
To ask the user something in a swal (Do you really want to..." and then do some things based in the answer of the user before the date are stored, don't work, as the JS Code ist not stopped until the user has made a choice.
Der swal is showed, but the data data are saved ( 3 ) immediately (no wait here).
To reach what I need, I had to change the logic.
New Logic
I had to decouple the check logic from the save:
No change to the check ( 1 )
Move the save of the data ( 3 ) in a separated function (SaveData())
Give out the swal ( 2 ) and then call SaveData() ( 3 ) from the swal functions.
My code to the swal:
if ((AvatarHochgeladen) && (!(AvatarUebernommen))) {
swal.fire({
title: '! Achtung !',
html: 'Sie haben eine eigene Grafik hochgeladen, diese aber nicht mit dem Button "Ihren upload übernehmen" als aktuellen Avatar übernommen. <br> Wenn Sie die Daten so speichern, geht Ihr hochgeladener Avatar verloren. <br> Wollen Sie Ihre hochgeladene Grafik als Avatar speichern?',
icon: 'question',
showCancelButton: true,
confirmButtonColor: 'blue',
cancelButtonText: 'Nein',
confirmButtonText: 'Ja',
}).then((result) => {
if (result.value) {
AvatarSpeichern = AvatarBase64;
SaveUserdata();
}
else { SaveUserdata(); }
})
}
So.. if the user chose "Yes", I replace a variable and call SaveData(), if the user chose "No" I directly call SaveData().
My conclusion:
As swal is "non blocking" (don't stop a running JS script), we have to split the logic and call (from the user choice depending) code from swal internal.
I Try:
function delete_rec_sub_button(id) {
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.isConfirmed) {
delete_rec_sub_button.yesKill();
}
});
delete_rec_sub_button.yesKill = function() {
//real code delete(id)
if('return sucess of delete'){
Swal.fire(
'Deleted!',
'Your file has been deleted.',
'success'
)
}else{
Swal.fire(
'error!',
'Unable to delete, current record is in use',
'error'
)
}
};
}

No update $scope in view after function

I have an array in my controller called this.selectedCourses. This array have some items which are showed in my view as a list.
After some steps I have this:
this.checkAddedCourses = function(studentCourses){
...
if(repeatedCourses.length != 0){
sweetAlert({
title: title,
text: text + ' ' + courseList,
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: confirmButtonText,
closeOnConfirm: false,
html: true
},
function(){
angular.forEach(repeatedCourses, function(repeatedCourse){
this.removeCoursePurchase(repeatedCourse);
}.bind(this));
swal("Deleted!", "Your purchase has been refreshed.", "success");
}.bind(this));
}
}
When the user click on button 'Remove' the items are removed fine from the array, I've already checked, but in my view I still seeing those items until I do something with that array. Is like it isn't refreshing the array after remove the elements.
Thanks.
PD: sweetAlert is a library for alerts.
Use $scope instead of this for data-binding on your view - so $scope.selectedCourses. Remember to pass $scope into your controller as a dependency.
Ok I've solved with the ´$apply´ function using it like this:
sweetAlert({
title: title,
text: text + ' ' + courseList,
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: confirmButtonText,
closeOnConfirm: false,
html: true
},
function(){
angular.forEach(repeatedCourses, function(repeatedCourse){
$rootScope.$apply(function() {
this.removeCoursePurchase(repeatedCourse);
}.bind(this));
}.bind(this));
swal("Deleted!", "Your purchase has been refreshed.", "success");
}.bind(this));

Categories