Best way to change messages from alert to labels - javascript

I used to display my validation as well as success/failure messages through alert pop-ups but now my requirement is to display the same using HTML label texts and make them disappear after a particular amount of time. I am currently using a timeout function:
if ($("#lblErrorMessage").text() != "") {
clrMsg = setTimeout(function(e) {
$("#lblErrorMessage").text("");
clearTimeout(clrMsg);
}, 5000);
}
This approach is very messy and there is no way to check whether the message is success (needs to be displayed for longer) or error/failure message (needs to be displayed for shorter period). Can anyone suggest a function which can be used throughout the page and also meet the requirements I want?
Thanks in advance

With an added class?
You don't show how you add the message in #lblErrorMessage...
But I suppose you can also add a class to it like "success" or "fail".
$("#lblErrorMessage").text("Some success messsage to user.").addClass("success");
removeMessage();
or
$("#lblErrorMessage").text("Some error messsage to user.").addClass("fail");
removeMessage();
Then, here is the new setTimeout function:
function removeMessage(){
if ($("#lblErrorMessage").text() != "") {
if $("#lblErrorMessage").hasClass("success"){
clrDelay = 5000;
}
else if $("#lblErrorMessage").hasClass("fail"){
clrDelay = 2500;
}
clrMsg = setTimeout(function(e) {
$("#lblErrorMessage").text("");
//clearTimeout(clrMsg); // No use for that.
$("#lblErrorMessage").removeClass("success fail"); // Remove classes for future messages.
}, clrDelay);
}
}

Related

Javascript -- any way to force a draw of new elements before processing?

I have a javascript function or two that takes a few seconds to process. I want to show an activity indicator so users don't think it's hung. I tried bootstrap animated progress bars and spin.js -- the problem is, I put the code for them before the processing, but the browser doesn't seem to update to show the new elements until after the function has finished. Obviously, an activity indicator that shows up after processing isn't incredibly useful. Is there a way to force the redraw before the processing occurs?
EDIT: here's an example code. This is from an HTA application, hence the pulling of files and such. I know the forced "wait" portion is a bad idea, usually, but in this program, files are opened and closed immediately, this is to prevent a race conflict and I just want to give it a quick 10 retry timeout before it tells them something is wrong. So, the problem is that this.spin() doesn't display its good until after the alert pops up.
Database.prototype.tryDatabase = function(fileName, toEdit, table, keepAlive) {
if (typeof keepAlive === 'undefined') keepAlive = false;
for (timeInd=0; timeInd < 5; timeInd++) {
var complete = this._addToFile(fileName, toEdit, table, keepAlive);
if (complete === false) {
var until = moment().valueOf() + 2000;
this.spin();
while (moment().valueOf() <= until) {;}
}
else break;
}
if (complete === false) window.alert("Database was locked for an extended period, please try again");
else if (!keepAlive) $('#added_to_db_modal').modal('show');
return complete;
}

Javascript confirmation cancel button issue [duplicate]

In my Rails 3 application I do:
render :js => "alert(\"Error!\\nEmpty message sent.\");" if ...
Sometimes, below this error message (in the same alert box) I see: "Prevent this page from creating additional dialogs" and a checkbox.
What does this mean ?
Is that possible not to display this additional text and checkbox ?
I use Firefox 4.
It's a browser feature to stop websites that show annoying alert boxes over and over again.
As a web developer, you can't disable it.
What does this mean ?
This is a security measure on the browser's end to prevent a page from freezing the browser (or the current page) by showing modal (alert / confirm) messages in an infinite loop. See e.g. here for Firefox.
You can not turn this off. The only way around it is to use custom dialogs like JQuery UI's dialogs.
You can create a custom alert box using java script, below code will override default alert function
window.alert = function(message) { $(document.createElement('div'))
.attr({
title: 'Alert',
'class': 'alert'
})
.html(message)
.dialog({
buttons: {
OK: function() {
$(this).dialog('close');
}
},
close: function() {
$(this).remove();
},
modal: true,
resizable: false,
width: 'auto'
});
};
Using JQuery UI's dialogs is not always a solution. As far as I know alert and confirm is the only way to stop the execution of a script at a certain point. As a workaround we can provide a mechanism to let the user know that an application needs to call alert and confirm. This can be done like this for example (where showError uses a jQuery dialog or some other means to communicate with the user):
var f_confirm;
function setConfirm() {
f_confirm = confirm;
confirm = function(s) {
try {
return f_confirm(s);
} catch(e) {
showError("Please do not check 'Prevent this page from creating additional dialogs'");
}
return false;
};
};
I designed this function to hopefully circumvent the checkbox in my web apps.
It blocks all functionality on the page while executing (assuming fewer than three seconds has passed since the user closed the last dialog), but I prefer it to a recursive or setTimeout function since I don't have to code for the possibility of something else being clicked or triggered while waiting for the dialog to appear.
I require it most when displaying errors/prompts/confirms on reports that are already contained within Modalbox. I could add a div for additional dialogs, but that just seems too messy and unnecessary if built-in dialogs can be used.
Note that this would probably break if dom.successive_dialog_time_limit is changed to a value greater than 3, nor do I know if Chrome has the the same default as Firefox. But at least it's an option.
Also, if anyone can improve upon it, please do!
// note that these should not be in the global namespace
var dlgRslt,
lastTimeDialogClosed = 0;
function dialog(msg) {
var defaultValue,
lenIsThree,
type;
while (lastTimeDialogClosed && new Date() - lastTimeDialogClosed < 3001) {
// timer
}
lenIsThree = 3 === arguments.length;
type = lenIsThree ? arguments[2] : (arguments[1] || alert);
defaultValue = lenIsThree && type === prompt ? arguments[1] : '';
// store result of confirm() or prompt()
dlgRslt = type(msg, defaultValue);
lastTimeDialogClosed = new Date();
}
usage:
dialog('This is an alert.');
dialog( 'This is a prompt', prompt );
dialog('You entered ' + dlgRslt);
dialog( 'Is this a prompt?', 'maybe', prompt );
dialog('You entered ' + dlgRslt);
dialog( 'OK/Cancel?', confirm );
if (dlgRslt) {
// code if true
}
This is a browser feature.
If you could, try to employ http://bootboxjs.com/, whit this library you can do the same of
alert("Empty message sent");
by writing:
bootbox.alert("Empty message sent", function(result) {
// do something whit result
});
You'll get a nice user interface too!

Disable the checkbox in "Prevent this page creating additional dialogs" ( Javascript alert ) [duplicate]

In my Rails 3 application I do:
render :js => "alert(\"Error!\\nEmpty message sent.\");" if ...
Sometimes, below this error message (in the same alert box) I see: "Prevent this page from creating additional dialogs" and a checkbox.
What does this mean ?
Is that possible not to display this additional text and checkbox ?
I use Firefox 4.
It's a browser feature to stop websites that show annoying alert boxes over and over again.
As a web developer, you can't disable it.
What does this mean ?
This is a security measure on the browser's end to prevent a page from freezing the browser (or the current page) by showing modal (alert / confirm) messages in an infinite loop. See e.g. here for Firefox.
You can not turn this off. The only way around it is to use custom dialogs like JQuery UI's dialogs.
You can create a custom alert box using java script, below code will override default alert function
window.alert = function(message) { $(document.createElement('div'))
.attr({
title: 'Alert',
'class': 'alert'
})
.html(message)
.dialog({
buttons: {
OK: function() {
$(this).dialog('close');
}
},
close: function() {
$(this).remove();
},
modal: true,
resizable: false,
width: 'auto'
});
};
Using JQuery UI's dialogs is not always a solution. As far as I know alert and confirm is the only way to stop the execution of a script at a certain point. As a workaround we can provide a mechanism to let the user know that an application needs to call alert and confirm. This can be done like this for example (where showError uses a jQuery dialog or some other means to communicate with the user):
var f_confirm;
function setConfirm() {
f_confirm = confirm;
confirm = function(s) {
try {
return f_confirm(s);
} catch(e) {
showError("Please do not check 'Prevent this page from creating additional dialogs'");
}
return false;
};
};
I designed this function to hopefully circumvent the checkbox in my web apps.
It blocks all functionality on the page while executing (assuming fewer than three seconds has passed since the user closed the last dialog), but I prefer it to a recursive or setTimeout function since I don't have to code for the possibility of something else being clicked or triggered while waiting for the dialog to appear.
I require it most when displaying errors/prompts/confirms on reports that are already contained within Modalbox. I could add a div for additional dialogs, but that just seems too messy and unnecessary if built-in dialogs can be used.
Note that this would probably break if dom.successive_dialog_time_limit is changed to a value greater than 3, nor do I know if Chrome has the the same default as Firefox. But at least it's an option.
Also, if anyone can improve upon it, please do!
// note that these should not be in the global namespace
var dlgRslt,
lastTimeDialogClosed = 0;
function dialog(msg) {
var defaultValue,
lenIsThree,
type;
while (lastTimeDialogClosed && new Date() - lastTimeDialogClosed < 3001) {
// timer
}
lenIsThree = 3 === arguments.length;
type = lenIsThree ? arguments[2] : (arguments[1] || alert);
defaultValue = lenIsThree && type === prompt ? arguments[1] : '';
// store result of confirm() or prompt()
dlgRslt = type(msg, defaultValue);
lastTimeDialogClosed = new Date();
}
usage:
dialog('This is an alert.');
dialog( 'This is a prompt', prompt );
dialog('You entered ' + dlgRslt);
dialog( 'Is this a prompt?', 'maybe', prompt );
dialog('You entered ' + dlgRslt);
dialog( 'OK/Cancel?', confirm );
if (dlgRslt) {
// code if true
}
This is a browser feature.
If you could, try to employ http://bootboxjs.com/, whit this library you can do the same of
alert("Empty message sent");
by writing:
bootbox.alert("Empty message sent", function(result) {
// do something whit result
});
You'll get a nice user interface too!

Alert Bar rather than alert box

I now have a script that prevents users from entering anything but a state abbreviation in the state field of my form. Thanks to gideon
I modified the script just a little to include an alert message when an invalid state is entered. But I don't really like it. I am going for an alert bar that flashes on the top of the page or maybe right below the field. Something that appears automatically when an incorrect abbreviation is entered and flash to grab the users attention and disappear after a few seconds. Any ideas or thoughts would be welcome! I am VERY open to suggestions! Thanks once again!
I am starting to think you guy's are not understanding me. This is the code I have:
<script>
function validateState(el) {
//put all states in this array.
var states = ["AK","AL","AR","AS","AZ","CA","CO","CT","DC","DE",
"FL","GA","GU","HI","IA",
"ID","IL","IN","KS","KY","LA","MA","MD","ME","MH","MI","MN","MO","MS","MT",
"NC","ND","NE","NH","NJ","NM","NV","NY","OH","OK","OR","PA","PR","PW","RI",
"SC","SD","TN","TX","UT","VA","VI","VT","WA","WI","WV","WY"];
for(var i=0;i< states.length;i++) {
if(el.value.toUpperCase() == states[i]) {
return true;
}
}
//clear element if it doesn't match a state
el.value = ""; //you could maybe do something else here.
alert('Invalid State Abbreviation, You must fix this before continuing')
document.getElementById("state").focus();
return false;
}
</script>
I am wanting to have a bar run across the screen if the statement returns false.
You can simple create an element that with be positioned above the view of the user (top: -100px etc). Once an invalid state has been entered you can use a Library like jQuery to animate it to top position 0. You can make it flash with a simple conditional statement inside of a setInterval();
I'm not sure if you are wanting to use jQuery but if you do then your code would look something like this:
//if the input is not what you expect..
if(input != state){
//drop the bar down
$("#bar").animate({
top: 0
}, 1500);//drop it in 1500 milliseconds.
//this is a lot like a loop that runs every 400 milliseconds..
setInterval(function () { <-------------------------------|
if ($("#bar").css("display") == 'none') { |
//if the bar is HIDDEN show it.. |
$("#bar").show(); |
} else { |
//else hide it. |
$("#bar").hide(); |
} |
}, 400);//<< EVERY 400 milli-seconds go here >-------------^
}
Of course this is just an example and can easily be translated back to traditional JavaScript.
Check out the jsFiddle.
I hope this is what you are looking for.
Adapting #Shawn's code, you'll need a function to show the bar and hide the bar, I've removed the code that makes the bar blink:
function ShowError(txt)
{
$("#bar").show();
$("#bar").text(txt);
$("#bar").animate({
top: 0
}, 1500);
}
function ClearError()
{
$("#bar").hide();
}
Then later on you will just do:
if(el.value.toUpperCase() == states[i]) {
ClearError();
return true;
} else {
ShowError("Please Enter a valid state");
}
See the whole code running here: http://jsfiddle.net/grFT7/8/
To make the bar disappear at some point you would do:
setInterval(function () { $("#bar").hide(); }, 5000);
//hide the bar every 5 secs (5000 milliseconds).
Use BootStrap's Alert. It is easy to use and looks cool.

Use both jQuery.checkbox & jQuery.field

I am trying to use two jQuery solutions on the one form, but I am unable to get the desired result after working on it for several hours.
The first jQuery solution enables a better look and feel
http://www.envirotalk.com.au/jquery/jquery-checkbox.htm
The second jQuery solution enables a limit to be set on the number of checkboxes selected.
http://www.envirotalk.com.au/jquery/jquery-field.htm
This is my attempt at combining the two.
http://www.envirotalk.com.au/jquery/combined.htm
I believe the problem relates to this line of code, but I cannot be certain.
setLimitSelection();
The outcome I am trying to achieve.
Look and feel; jquery-checkbox
Limit to the number of checkboxes one
can select; jquery-field
The error message; jquery-field
Clearing the extra field value once
exceeded limit; jquery-field.
If someone has the time to take a look and help me, that would be greatly appreciated.
The two plug-ins are probably conflicting with each other, since the code that you're using is the same as the ones given in the individual examples. For limiting checkboxes that can be selected, you can try this:
function setLimitSelection(){
$("input[type=checkbox]").click(function(){
var checkboxes_to_allow = 3;
if($('input[type=checkbox]:checked').length == (checkboxes_to_allow+1)){
//show error message
return false;
} else {
//clear message
}
});
}
I think the code is clear enough to not need comments?
Hello I think you can solve the problem with a small status variable like checkfield:
var checkfield = false;
$("input[name ='name']").limitSelection({
limit: 3,
onfailure: function (n){
checkfield = true;
return false;
}
}).click(function (){
if (field6error)
{
$(this).checkBox('changeCheckStatus', false);
checkfield = false;
alert("Not more than 3 values!")
return false;
}});

Categories

Resources