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.
Related
This is my school project. I have tried to do it as simple as possible, just to change background color in web page etc..
I work with an external device with two buttons (microbit a and b) -connected in serial port, writing data string "aa" or "bb". Then python code reads it inside for ever loop and writes it in json file, where this code should be able to enter in. With these changing json time stamps, this code should read which button was pressed latest and then do what is written in conditions.
json files reference time is changing all the time, by the button press.
I am very thankful for any help, we have been doing this project already quite long, this is final stage but as you see ,but i am not yet there.
As this does not execute anything after get json line... it did once, and till final >>if, but then it stopped..why? I dont know.. I am not good enough in this.
Final part of the code curly braces etc, i cant anymore count which one is too much or >>what is missing?! ...
my json example: {"REF": 1624391142, "aa": 1624391140, "bb": 1624391142}
$(document).ready(function () {
console.log("jQuery starts");
var d = new Date();
var time = d.getTime();
setInterval(function () {
// loop that reads every 2 sec json file,
$.getJSON("data.json"),
function (json) {
console.log("test", time);
//what is REF-time <= time
if (time <= json.REF) {
// any changes?
time = json.REF;
console.log(" REF", time);
pressedBtn = "";
jQuery.each(json, function (key, value) {
//searhing
if (value == time && key != "REF") {
pressed = key;
console.log("Working");
}
if (pressedBtn == "aa") {
$("body").show("active"); //background color change
console.log("pressed", pressedBtn);
$("#toshow").show("toshow"); // comment div
}
if (pressedBtn == "bb") {
$("#toshow").hide("toshow"); //comment div
console.log("pressed", pressedBtn);
}
});
}
};
}, 2000);
});
I think I understood you and maybe this is your solution check this
$(document).ready(function(){
setTimeout(doSomething,2000);
});
function doSomething(){
console.log("do something");
setTimeout(doSomething,2000);
}
this function is execute every 2 seconds like you want in your code
i hope i have help you
Ok, here is a pick what was wrong. I somehow had added parenthes there right side of the json, where is shouldnt be, thats how the whole block got stuck, i am appologising for taking anyones time. All these marks and syntaxes make one crazy..
Thank you anyway, this community is amazing
in the vis.js timeline there is an option to have nested groups, that expands and collaps on clicks, however if i reload the site after i have expandede some of the groups, they all reset back to collapsed state.
what i would like, was a way to set a cookie or session when i expand or collapses the group, that way i could read that session or cookie on reload and inform the script if XX group should be expandede or not.
unfortunatly i ain't that good at js. and have a hard time figuring out how to get the Group information needed.
what i have found is this code snippet
ItemSet.prototype._onGroupClick = function (event) {
var group = this.groupFromTarget(event);
if (!group || !group.nestedGroups) return;
var groupsData = this.groupsData;
if (this.groupsData instanceof DataView) {
groupsData = this.groupsData.getDataSet();
}
group.showNested = !group.showNested;
var nestedGroups = groupsData.get(group.nestedGroups).map(function (nestedGroup) {
if (nestedGroup.visible == undefined) {
nestedGroup.visible = true;
}
nestedGroup.visible = !!group.showNested;
return nestedGroup;
});
groupsData.update(nestedGroups);
if (group.showNested) {
util.removeClassName(group.dom.label, 'collapsed');
util.addClassName(group.dom.label, 'expanded');
} else {
util.removeClassName(group.dom.label, 'expanded');
var collapsedDirClassName = this.options.rtl ? 'collapsed-rtl' : 'collapsed';
util.addClassName(group.dom.label, collapsedDirClassName);
}
};
That seams to handle the Onclick funtion that expand and collaps the group, what i don't know is how to set a cookie with the group information.
i just need to have the cookie spit out like Groupid=x ..
is there a way to do that, or am i on a wild goosechase and looking at this completely wrong?
thanks for any help
Update
After i have looked it over once more, i am certain i am the right place to make the cookie ( to remember the state of the group )
if i place a alert like this
if (group.showNested) {
alert("something");
util.removeClassName(group.dom.label, 'collapsed');
util.addClassName(group.dom.label, 'expanded');
}
So i can make something when i click the group to expand it, what i still can't figure out is how to get the Group id, that i need for my cookie to remember.
so my clients can leave the site and return and it will remember what gruops where expandede and collapsed.
so any help with the Groupid or how to find it would be much appriciated.
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);
}
}
What would be the most efficient way to show and hide iframes in a page every x time?
I was thinking on using a setInterval on a function that uses jQuery's hide and show but this seems inneficient and not very scalable if I needed to hide and show 1 out of 10 iframes in one page that I would also need to hide and show.
$(document).ready(function(){
setInterval(function() {
if ($('#basic').is(":visible") && $('#advanced').not(":visible") ) {
$('#basic').hide();
$('#advanced').show();
}else if($('#basic').not(":visible") && $('#advanced').is(":visible")) {
$('#basic').show();
$('#advanced').hide();
}else if($('#basic').is(":visible") && $('#advanced').is(":visible")) {
$('#basic').hide();
$('#advanced').show();
};
}, 30000);
});
Each id refers to 1 iframe so right now I am only dealing with 2 iframes. The reason I have that last if else statement is because both iframes are being displayed when I load the page.
Just a snippet since the OP asked for it. Posting as an answer so I can format the code a bit better. (warning: I haven't 100% tested it myself yet, this isn't meant as a copy/paste implementation.)
This should show all the hidden frames and hide all the visible frames every 30 sec.
You can obviously easily extend it to only show/hide specific nodes that you can reference by id since frames[theFramesID] will give you the reference and visible status. If you don't need to be able to access specific frames, you can obv simplify this and use an array instead of an object.
Just using some form of loop and caching your nodes instead of requerying the same node over and over again will already increase the scalability. Since you don't need to change the code once you add another frame.
One could probably replace the vanilla functions I used with jquery specific ones if needed. I'm not sure which version of jquery has built-in reduce.
$(document).ready(function(){
var frames = $('iframe').reduce(function ( accumulator, frame ) {
accumulator[frame.id] = {
'reference' : frame,
'visible' : frame.is(":visible")
};
return accumulator;
}, {});
setInterval(function() {
Object.keys(frames).forEach(function ( id ) {
var frame = frames[id];
if (frame.visible) {
frame.visible = false;
frame.reference.hide();
}
else {
frame.visible = true;
frame.reference.show();
}
});
}, 30000);
});
I have a contact script. It uses jQuery for it's ajax requests and animations.
I also use it with a hashchange plugin to fix the back button. The slow part lies there.
After finishing the animation of the 'flip', the form fades slowly. The browsers seem to block for a sec. I'm trying to make it snappy (no blocking).
Here is the function responsible for handling the hash change event:
handleHashChange : function () {
// Get the name of the object and cache it
var self = this,
// Get the current hash
hash = window.location.hash,
// Cache the form height var
formHeight = '';
// If the hash is #send or #error, don't do anything
if (hash === "#sent" || hash === "#error") {
return;
}
// Change the page title back to the default
if(self.documentTitle && self.documentTitle != undefined) {
document.title = self.documentTitle;
}
// Reset all inputs in the form
self.inputs.val('').removeAttr('checked').removeAttr('selected');
// Get the height of the form
formHeight = self.getHeight(self.form);
// Show the transition
self.showTransition(self.response, formHeight, function() {
// Show the form
self.form.fadeIn('fast', function() {
// Show the button
self.button[0].style.display = 'block';
// Focus the first input
self.inputs[0].focus();
})
})
}
The whole code can be seen from the link below, it's fully documented:
http://www.coolcontact.co.cc/beta/1.3/js/main.js
You can see I have used a lot of tips I found on the internet to optimize this script, except using javascript's native 'for' in place of '$.each()' , but it's not that big of a deal here.
If anyone wants to see the slowness, try sending an empty message (validation is disabled) from the link below then click the back button in your browser:
(note: it's not in English, but guess it's pretty self-explanatory ^^)
http://www.coolcontact.co.cc/beta/1.3/
So how can I make it more snappy?
I think it's pretty quick already, but here's something I noticed with your code.
This "if" statement is a bit redundent.
if(self.documentTitle && self.documentTitle != undefined) {
document.title = self.documentTitle;
}
The call to "self.documentTitle" will return evaluate to "false" if its value is "undefined", so you don't need the second "self.documentTitle != undefined".
You could just use the follwing instead:
if(self.documentTitle){
document.title = self.documentTitle;
}
Remember, the values false, null, undefined, 0 and an empty string all evaluate to a false boolean value.