Alert box error - javascript

I have to allow only alphabets to the text box. I have validated through JavaScript on text box using "on blur". The alert from the JavaScript remains open even though I try to close.
Find the demo link and the JavaScript below.
Note: Type any non-alphabet in the text box 1 and press tab or click on somewhere else from the following link.
http://demo.acclary.com/test.aspx
The JavaScript I used is, below:
function checkalphabets(textbox) {
var pattern = /^[a-zA-Z\s]+$/;
if (!pattern.test(textbox.value)) {
modal({
type: 'warning',
title: 'Warning',
text: 'Only Alphabets allowed!',
center: false,
});
setTimeout(function () { textbox.focus(); }, 1);
exit;
return false;
}
return true;
}
$('.modal-btn').click(function() {
$('#modal-window').hide();
});

You just need to add following line of code in the modal function:
callback: function(){ $("#myTextBox").focus();}
So After change, it will be like
modal({
type: 'warning',
title: 'Warning',
text: 'Only Alphabets allowed!',
center: false,
callback: function(){ $("#myTextBox").focus();}
});
That's all.
I have created fiddle using the Modal plugin that you are using in the page.
http://jsfiddle.net/7kpsv1p4/1/

change on-blur to onchange
small changes in your code
function checkalphabets(textbox) {
var pattern = /^[a-zA-Z\s]+$/;
if (!pattern.test(textbox.value)) {
textbox.focus();
modal({
type: 'warning',
title: 'Warning',
text: 'Only Alphabets allowed!',
center: false,
});
return false;
}
return true;
}
I hope this will work.

If you use onblur and focus on the textbox together the alert box will always show in the screen, because after focusing the textbox you are closing the modal alert means that you are re-belurring the textbox.
So it's better to use :
the onchange event.
Or the onKeyup event.
Note: Using the onkeyup is a better approach to refocus the textbox safely.
And try to focus on the textbox right before showing the alert, so when you close the alert the textbox will be already focused.
EDIT:
Here's a DEMO Fiddle using the onkeyup event but a simple alert, and here's the code:
function checkalphabets(textbox) {
var pattern = /^[a-zA-Z\s]+$/;
if (!pattern.test(textbox.value)) {
setTimeout(function () { textbox.focus(); }, 1);
alert('This is wrong');
exit;
return false;
}
return true;
}
It fires whenever you type a wrong character and still focuses in teh textbox.

Related

Validation for tr insert with alertbox (confirm.js) not working

I've been trying to create a dynamic table that lets the user insert rows with textboxes and confirm the data/insert it on database by clicking a confirm button. The button works just fine, it inserts the table row on click, but i need a validation where the textboxes can't be blank and i can't make it work inside the function.
i've tried creating variables for the data on the textboxes, and used a simple if to confirm they are not empty, but the confirm button keeps adding the table rows without displaying the alert
$(function tableConfirm(){
$(document).on('click','.btnConfirm', function(){
var error=0;
var campo1 = document.getElementById("campo1").value;
var campo2 = document.getElementById("campo2").value;
var campo3 = document.getElementById("campo3").value;
var campo4 = document.getElementById("campo4").value;
//Html insertion
var content='<tr><td><label class="checkContainer"><input type="checkbox"><span class="checkmark"></span></label></td><td id="texto1">'+campo1+'</td><td id="texto2">'+campo2+'</td><td id="texto3">'+campo3+'</td><td id="texto4">'+campo4+'</td><td><button class="eliminar">X<!--</Button><<i class="far fa-edit"></i></button>--></td></tr>';
$(this).parents('tr').remove();//this is to remove the textboxes before inserting the row data
$('tbody',currentView).append(content);//this appends the row data
//Validation not working
if(document.getElementById("texto1").value==""){
$.alert({
useBootstrap:false,
columnClass:'small',
title:'Error!',
content:'you must fill all the blanks!',
icon:'fas fa-exclamation-triangle',
type:'red',
typeAnimated:true,
buttons:{
tryAgain:{
text:'Ok',
btnClass: 'btn-red',
action: function(){
}
}
}
});
}
//This alertbox should only be displayed if the row has no blank spaces
else
$.alert({
useBootstrap:false,
columnClass: 'small',
title: 'Success!',
content: 'Task inserted!',
type: 'green',
icon:'fas fa-check-circle',
typeAnimated: true,
buttons: {
tryAgain: {
text: 'Ok',
btnClass: 'btn-green',
action: function(){
}
},
}
});
});
});
I expect the code to alert the user when the textboxes aren't filled, but it always inserts the task and shows the respective alert.
Thank you for your time, I appreciate any kind of help!
a TD element has no value but innerHTML so repleace the following :
wrong:
if(document.getElementById("texto1").value=="")
Correct:
if(document.getElementById("texto1").innerHTML=="")

Can I have multiple Sweet Alert 2 PopUps?

My HTML/Javascript app uses a modal popup which I created using sweet Alert 2. Let's call this "Alert1".
Alert1 is using custom HTML and there is a button inside that HTML which I want to trigger another sweet alert 2 modal popup, we'll call this one "Alert2".
Alert2 has two options. "confirm" or "cancel" If the user clicks "cancel" I want to return to Alert1.
Here is the catch: The custom HTML for Alert1 is editable therefore, I can't just re-invoke the code that originally launched the alert, because this would show the old HTML.
This is what I have tried:
function clickButton(){ //This function will be attached to the button in Alert1
var currentSwal = document.getElementById('swal2-content').innerHTML;
swal({
title: "Confirm 'Remove Script Page'",
text:
"Are you sure you want to remove this page from the script?",
type: "warning",
showConfirmButton: true,
showCancelButton: true
}).then(function(dismiss) {
if (dismiss.dismiss == "cancel" || dismiss.dismiss == 'overlay') {
swal.close;
swal({
html: currentSwal,
showConfirmButton: false,
customClass: 'swal-extra-wide',
showCloseButton: true
});
} //end if
else {
//go ahead and delete the script page
} //end else
});
}//end function
My above solution does not work. It is a bit hard to explain, but basically, the HTML code gets broken and things just don't work properly.
TLDR/My question: Is there a way to have multiple SweetAlert2 alerts? (i.e. launch alert2 from alert1 and then close alert2, returning the view to alert1?
Yes you can ,
var modals = [];
modals.push({title: 'title Of Modal1', text: 'text1' });
modals.push({title: 'title Of Modal2', text: 'text2' });
swal.queue(modals);
References
Question 38085851 Answer 1
make a for loop for 3 and use toast not sweet alert and it will be works

trying to check whether string is empty or not, but the check doesn't work properly

I am trying to check whether the textarea isn't empty. If yes: Then disable the submit button, if not: then enable it. However whenever I do back-space it disables the button (you could argue that it checks on keydown whether it's empty or not, and when it is it disables), so let's say that isn't even a big of a problem... However when I write something in my textarea it doesn't enable the submit button, it keeps it disabled with the first letter, when I press a second key it "recognizes" that the input isn't empty and enables it.
How the 2 functions look like:
function chatArea(tracker) {
let textArea = ($('<textarea/>', {
'col': 50,
'row': 4,
'class': 'form form-control',
'name': 'textareaSubmitData',
'id': 'textareaSubmitData',
'maxLength': 200,
'placeholder': 'Hey there! Feel free to start chatting!'
})).on('keydown', function() {
tracker.chatString = $(this).val();
if($(this).val() == '') {
$('#submitBtnTextArea').attr('disabled', 'disabled');
return;
} else {
$('#submitBtnTextArea').removeAttr('disabled');
}
});
return textArea;
}
function submitBtnTextArea(tracker) {
let btn = ($('<button/>', {
'type': 'submit',
'class': 'btn btn-success',
'name': 'submit',
'id': 'submitBtnTextArea'
})).html('<li class="fa fa-send"> Send!</li>');
return btn;
}
Any reason why it disables and enables without a logical reason behind it?
I think you should use keyup in this case.
Keydown is triggering before actually deleting the character from the textarea, so when you execute the anonymous method, the letter is still there. That's why when you enter the first character, the button is still disabled because there are 0 characters. When you enter a new character, then there is 1 character, and the button becomes enabled.

SweetAlert: block event like JavaScript Alert()

I have a function that asks users for confirmation when selecting a value from a Select dropdown. When using the regular JavaScript confirm(), the change event does not get the newly selected value without clicking on confirm. This can be seen in this Fiddle.
When a value is selected, and the user clicks cancel, the same value is shown in an alert dialog. When the user clicks confirm, the newly selected value is displayed.
However, I'd like to use SweetAlert. When changing the value with SweetAlert, the change happens without even selecting confirm or cancel. As demonstrated in this Fiddle. When a value is selected, an alert dialog is displayed right after selection, unlike with the pure JS Confirm() which blocks the event somehow.
I'd like to achieve the same effect as the JS confirm(), where the change event is not triggered while the user has not clicked confirm or cancel, when using SweetAlert.
Aside from both Fiddles which demonstrate the problem, here's the code I'm using:
Some simple HTML select:
<select id="dropdownId">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
The JavaScript confirm() version (which does what it needs to do):
var prev_val;
$('#dropdownId').focus(function () {
prev_val = $(this).val();
}).change(function (e) {
var select = this;
$(this).blur();
var success = confirm('Are you sure you want to change the Dropdown?');
if (success) {
// Other changed code would be here...
} else {
$(this).val(prev_val);
return false;
}
});
$('#dropdownId').change(function (e) {
alert($(this).val());
});
And the SweetAlert version, where the change event should wait on the response of the SweetAlert dialog.
var prev_val;
$('#dropdownId').focus(function () {
prev_val = $(this).val();
}).change(function (e) {
var select = this;
$(this).blur();
return swal({
title: "Are you sure?",
text: "Change dropdown select?",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes!",
cancelButtonText: "No!",
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm) {
return true;
} else {
$(select).val(prev_val);
return false;
}
});
});
$('#dropdownId').change(function (e) {
alert($(this).val());
});
Edit:
Moving the logic to the confirm handler of the dialog does not solve this issue. I'm using a framework (Apache Tapestry) which listens for a change event on the select. When using the solution as RRR stated, in this fiddle, the change event still happens. Which still causes it to fire an event to my backend, unlike with the JS confirm() which does not change the value until confirm was clicked.
Edit 2:
My problem doesn't really seem to be that clear. Here are the steps I undertake to try and show what the root of the problem is:
When using the JS confirm from this fiddle. The following happens:
I click on a value
It asks for confirmation
On confirm, it logs the new value. On cancel, it logs the original value.
When using the SweetAlert dialog, using this fiddle. The following happens:
I click on a value
It logs the newly selected value, before confirming/cancelling
On confirm/cancel I can execute logic.
When using the SweetAlert dialog, as edited by RRR in this fiddle. The following happens:
I click on a value
It logs the newly selected value, before confirming/cancelling
On confirm/cancel, it shows an alert
Both my and RRR's SweetAlert example have the same issue. Namely, step 2. Not the fact that it logs, but the fact that the value actually changes. Unlike in the first pure JS example, where the value does NOT change unless confirm is clicked.
Ok. Here is the issue.
You call 2 different actions at onchange event:
1- The big function...
2- A test alert.
Both occur at the same time. <-- Here lies the confusion!
This is why it appeared to you that swal doesn't "wait" to get an answer from the user.
Try this... And look at your console.log messages:
var prev_val;
$('#dropdownId').focus(function () {
prev_val = $(this).val();
console.log("On focus event value : "+prev_val); // ADDED
}).change(function (e) {
var select = this;
console.log("At the BEGINNING of the change event : "+$(select).val()); // ADDED
$(this).blur();
swal({ // REMOVED return in front of it
title: "Are you sure?",
text: "Change dropdown select?",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes!",
cancelButtonText: "No!",
closeOnConfirm: true, // These are default.. useless to specify
closeOnCancel: true // These are default.. useless to specify
},
function (isConfirm) {
if (isConfirm) {
//return true; // no need to return anything - commented out
console.log("swal YES");
console.log("At the END of the change event : "+$(select).val());
} else {
$(select).val(prev_val);
//return false; // no need to return anything - commented out
console.log("swal NO");
console.log("At the END of the change event : "+$(select).val());
}
// Here is a callback final test alert!
alert("Callback alert: "+$(select).val());
});
});
/*$('#dropdownId').change(function (e) { // This was a bad idea ! ;)
alert($(this).val());
});*/
In my case sweet alert 2 was blocking my binded event handlers:
Swal.fire( // Not works - Nothing will happen onclick
{html: `<button id="btn1" onclick="alert('clicked')">Delete</button>`,
)
So i binded the event handlers in javascript instead, on modal open:
Swal.fire(
{html: `<button id="btn1">Delete</button>`,
onOpen: () => {document.querySelector('#btn1').onclick = () => {alert('clicked')}
)

Dynamicly Added Input is not updating on the screen

I am new to JavaScript so bear with me here.
I have this code below that checks a text input fields value, if it matches then I fire off my Custom Dialog object/function which shows a Dialog modal window.
Now my goal is to Clear out the text input that fired the Dialog to open if the Cancel button is clicked
I have a Callback function named cancelCallback that I can pass into my Dialog function.
In my example you can see I have cached the Input field selector hostnameSelector and then passed it into my callback.
Below that you can see I print out the object to the Console. The Console shows my NEW value for the text field but it does not update on the screen.
This could be possibly because the Text Input filed is Dynamicly added to the screen/DOM?
Any ideas on how I can get it working? I am also able to use the latest jQuery if needed to help
// Show Notice if Hostname Matches the Domain Name
$(document).on('change','div.hostName > input',function() {
// cached Input Selector
var hostnameSelector = $(this);
var hostName = $(this).val();
var domainName = $("#domainName").val();
var pattern = new RegExp(domainName + "$","g");
if ( hostName.match(pattern) != null ) {
var msg = 'Are you sure you want to delete action?';
zPanel.dialog.confirm({
heading: 'ATTENTION',
message: msg,
width: 300,
cancelCallback: function (hostname) {
hostnameSelector .value = 'hi';
console.log(hostnameSelector);
},
cancelButton: {text: 'Cancel', show: true, class: 'btn-default'},
okButton: {text: 'Confirm', show: true, class: 'btn-primary'},
});
}
});
CancelCallback should set the new value by calling:
hostnameSelector.val("hi")

Categories

Resources