I am trying to make a form validation in 2 steps. One client side, one server side. I managed to get some parts of the client check working. I am experiencing peculiar bugs... The code:
//global vars
var form, cegnev, cegnevInfo, cegcim, cegcimInfo, cegemail, cegemailInfo, cegkapcs, cegkapcsInfo, cegbeosz, cegbeoszInfo;
form = $("#jelentkezes");
cegnev = $("#ceg_nev");
cegnevInfo = $("#ceg_nevInfo");
cegcim = $("#ceg_cim");
cegcimInfo = $("#ceg_cimInfo");
cegemail = $("#ceg_cim");
cegemailInfo = $("#ceg_emailInfo");
cegkapcs = $("#ceg_kapcs");
cegkapcsInfo = $("#ceg_kapcsInfo");
cegbeosz = $("#ceg_beosz");
cegbeoszInfo = $("#ceg_beszInfo");
(function () {
"use strict";
// this function is strict...
$(document).ready(function () {
function validateCegemail() {
//testing regular expression
var a = $("#ceg_email").val(), filter = /^(([^<>()\[\]\\.,;:\s#\"]+(\.[^<>()\[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
//if it's valid email
if (filter.test(a)) {
cegemail.removeClass("elizelte");
cegemailInfo.removeClass("elizelte");
cegemailInfo.text("Jó!");
cegemail.addClass("lotto");
cegemailInfo.addClass("lotto");
return true;
} else {
//if it's NOT valid
cegemail.removeClass("lotto");
cegemailInfo.removeClass("lotto");
cegemail.addClass("elizelte");
cegemailInfo.text("E-mail formátuma nem megfelelő! pl: valaki#vhalahol.hu");
cegemailInfo.addClass("elizelte");
return false;
}
}
function validateCegnev() {
//if it's NOT valid
if (cegnev.val().length < 7) {
cegnev.removeClass("lotto");
cegnevInfo.removeClass("lotto");
cegnev.addClass("elizelte");
cegnevInfo.text("Cég névnek több mint 7 betűből kell állnia!");
cegnevInfo.addClass("elizelte");
return true;
} else {
//if it's valid
cegnev.removeClass("elizelte");
cegnevInfo.removeClass("elizelte");
cegnevInfo.text("Jó!");
cegnev.addClass("lotto");
cegnevInfo.addClass("lotto");
return false;
}
}
function validateCegbeosz() {
//if it's NOT valid
if (cegbeosz.val().length < 4) {
cegbeosz.removeClass("lotto");
cegbeoszInfo.removeClass("lotto");
cegbeosz.addClass("elizelte");
cegbeoszInfo.text("Beosztás minimum 4 betűből kell, hogy álljon!");
cegbeoszInfo.addClass("elizelte");
return true;
} else {
//if it's valid
cegbeosz.removeClass("elizelte");
cegbeoszInfo.removeClass("elizelte");
cegbeoszInfo.text("Jó!");
cegbeosz.addClass("lotto");
cegbeoszInfo.addClass("lotto");
return false;
}
}
function validateCegkapcs() {
//if it's valid
var a = $("#ceg_kapcs").val(), filter = /^(\b[a-zA-Z.-]+\b.*){2,4}$/;
if (filter.test(a)) {
cegkapcs.removeClass("elizelte");
cegkapcsInfo.removeClass("elizelte");
cegkapcsInfo.text("Jó!");
cegkapcs.addClass("lotto");
cegkapcsInfo.addClass("lotto");
return true;
} else {
//Ha if it's NOT valid
cegkapcs.removeClass("lotto");
cegkapcsInfo.removeClass("lotto");
cegkapcs.addClass("elizelte");
cegkapcsInfo.text("Kis és nagybetű, szóköz és kőtőjel csak a megengedett!");
cegkapcsInfo.addClass("elizelte");
return false;
}
}
//On blur
cegnev.blur(validateCegnev);
cegemail.blur(validateCegemail);
cegkapcs.blur(validateCegkapcs);
cegbeosz.blur(validateCegbeosz);
//On key press
cegnev.keyup(validateCegnev);
cegemail.keyup(validateCegemail);
cegkapcs.keyup(validateCegkapcs);
cegbeosz.keyup(validateCegbeosz);
I don't know whats appropriate or not posting the whole code, or just the parts I have a genuine problem with, excuse me for not knowing that. My problem is that 2 validations work flawlessly. One that does "cegnev" and one that does "cegkapcs". The other two screw themselfs up, but differently. The cegemail does NOT work at ALL. cegbeosz does work to an extent but does NOT change the text.
The "testing" website can be checked at www.tudatoskommunikacio.hu/gergo if u want to check out the html part of it. I am quite new to javascript, and I do beleive that is causing the erros. I tried to narrow down my mistakes by using Jlint, but beside a few problems, that I read across the web I can live with, nothing stands out as a mayor flaw. Thanks for the help, I am quite desperate here...
It's just a copy-paste error by the look of it. At the top of your code:
cegcim = $("#ceg_cim");
cegcimInfo = $("#ceg_cimInfo");
cegemail = $("#ceg_cim");
cegemailInfo = $("#ceg_emailInfo");
You are selecting the ceg_sim id for the cegemail variable
Your other issue is also just a trivial spelling mistake:
cegbeosz = $("#ceg_beosz");
cegbeoszInfo = $("#ceg_beszInfo");
You're missing an "o".
I strongly recommend using a javascript debugger in future to catch these trivial mistakes.
Related
I made a set of event listeners:
var fname = document.getElementById("fName");
var ssn = document.getElementById("ss");
var zip = document.getElementById("zip");
var hphone = document.getElementById("hphone");
var wphone = document.getElementById("wphone");
var mphone = document.getElementById("mphone");
var dob = document.getElementById("dateObirth");
if (ssn.addEventListener) {
console.log("Validating");
fname.addEventListener("change", validatefname, false);
ssn.addEventListener("change", validateSSN, false);
zip.addEventListener("change", validateZip, false);
hphone.addEventListener("change", validateHPhone, false);
wphone.addEventListener("change", validateWPhone, false);
mphone.addEventListener("change", validateMPhone, false);
dob.addEventListener("change", validateDOB, false);
} else if (ssn.attachEvent) {
console.log("Validating_02");
fname.attachEvent("onchange", validatefname);
ssn.attachEvent("onchange", validateSSN);
zip.attachEvent("onchange", validateZip);
hphone.attachEvent("onchange", validateHPhone);
wphone.attachEvent("onchange", validateWPhone);
mphone.attachEvent("onchange", validateMPhone);
dob.attachEvent("onchange", validateDOB);
}
the elements are inputs in my html file and the ids are all correct.
in this instance the different validate functions never happen. even when I change the info inside the input fields, they never run like they are supposed to.
now if I write the code like this;
var fname = document.getElementById("fName");
var ssn = document.getElementById("ss");
var zip = document.getElementById("zip");
var hphone = document.getElementById("hphone");
var wphone = document.getElementById("wphone");
var mphone = document.getElementById("mphone");
var dob = document.getElementById("dateObirth");
if (ssn.addEventListener) {
console.log("Validating");
fname.addEventListener("change", validatefname(), false);
ssn.addEventListener("change", validateSSN(), false);
zip.addEventListener("change", validateZip(), false);
hphone.addEventListener("change", validateHPhone(), false);
wphone.addEventListener("change", validateWPhone(), false);
mphone.addEventListener("change", validateMPhone(), false);
dob.addEventListener("change", validateDOB(), false);
} else if (ssn.attachEvent) {
console.log("Validating_02");
fname.attachEvent("onchange", validatefname);
ssn.attachEvent("onchange", validateSSN);
zip.attachEvent("onchange", validateZip);
hphone.attachEvent("onchange", validateHPhone);
wphone.attachEvent("onchange", validateWPhone);
mphone.attachEvent("onchange", validateMPhone);
dob.attachEvent("onchange", validateDOB);
}
with a set of parentheses after each validate function, then the validate functions will always occur regardless of if I have entered any data into the input fields or changed said data to supposedly be correct.
so basically, the one thing that is broken is whether the validate functions always occur regardless of if I've entered information or they never occur.
Can anyone tell me what I am doing wrong here? I just want the functions to occur only if I enter information into the input field and or change preexisting data.
Here is one of the validate functions, they all are pretty much the same:
function validateSSN(){
console.log("Validate ssn");
var ssn = document.getElementById("ss");
var errorDiv = document.getElementById("ssError");
var ssnPattern = /^\d{3}-?\d{2}-?\d{4}$/;
try {
if(ssnPattern.test(ssn.value) === false) {
throw "Please provide a valid Social Security Number.";
}
ssn.style.background = "";
errorDiv.innerHTML = "";
errorDiv.style.display = "none";
}
catch(msg) {
errorDiv.innerHTML = msg;
errorDiv.style.display = "block";
// change input style
ssn.style.background = "rgb(255,233,233)";
}
}
As far as I can see with a more limited example it appears to work:
function validateSSN(){
console.log("Validate ssn");
var ssn = document.getElementById("ss");
var errorDiv = document.getElementById("ssError");
var ssnPattern = /^\d{3}-?\d{2}-?\d{4}$/;
try {
if(ssnPattern.test(ssn.value) === false) {
throw "Please provide a valid Social Security Number.";
}
ssn.style.background = "";
errorDiv.innerHTML = "";
errorDiv.style.display = "none";
}
catch(msg) {
errorDiv.innerHTML = msg;
errorDiv.style.display = "block";
// change input style
ssn.style.background = "rgb(255,233,233)";
}
}
var ssn = document.getElementById("ss");
if (ssn.addEventListener) {
console.log("Adding event listener");
ssn.addEventListener("change", validateSSN, false);
}
<input id="ss" />
<div id="ssError"></div>
As for why the version with parentheses always run, that's because they're being called when the event listeners are being created rather than when the event is triggered.
I am not sure what exactly I did to fix this problem, I just continued working on other parts of the website and the validation code suddenly started working. Sorry I don't have a specific answer to resolve the issue for anyone in the future, but my best suggestion is just muddle through and work on other aspects of the project and broken stuff may just snap into place and work properly.
I'm making some Adobe Bridge (CS 5.1) plugins.
My problem is that I cannot figure out how to ensure that their respective menu items will be greyed out unless the user has selected valid items for the script.
I can reach the desired state by coding something like
function greyOutMenu () {
var doc = application.document;
var these = [];
these = doc.selections;
menuItem.enabled = true;
if ( these.length < 1 ) {
menuItem.enabled = false;
return;
}
for ( var i in these ) {
if ( these[i] /* is invalid */ ) { menuItem.enabled = false;
return;
}
}
but how do I get this check to run directly when the menu is opened? If I use
myMenu.onSelect = greyOutMenu();
It just runs the check on startup instead of when the menu is opened!
Okay, I figured out what was wrong. I have changed it to...
function greyOutMenu () {
var doc = app.document;
var here = doc.presentationPath;
var thisFolder = Folder ( here );
if ( decodeURI ( thisFolder.name ) === "correct folder name" ) { menuItem.enabled = true; }
else { menuItem.enabled = false; }
if (!app.document.selectionsLength > 0 ) { menuItem.enabled = false; }
}
menuItem.onDisplay = greyOutMenu;
I could have sworn that I had already tried menuItem.onDisplay, but I must have made a syntax error.
Also, In my case it is enough to be in the right folder and have something selected, as the files are added directly by a camera. More complex checks are instead added to the function itself, to prevent stuttering every time the menu is opened.
So, I have a 'mini-game' in Vue.js which let's you 'fight'.
I am trying to make it that after someone 'dies' the game declares the winner and then asks if you want to play again.
All good until there,but when i'm trying to make it so after you clicked that you want to play again, to reset your health and 'monster\'s' health back to 100, it just doesn't work.
Here's my code, where i reset everything, it runs, i've put console logs but it does nothing:
checkWinner: function() {
if(this.mHp <= 0) {
if (confirm('You won! Play again?')) {
this.startGame();
} else {
this.gameIsActive = false;
}
return true;
} else if (this.pHp <= 0) {
if (confirm('You lost! Play again?')) {
this.startGame();
} else {
this.gameIsActive = false;
}
return true;
}
return false;
}
}
Also, here's the full code if you wanna take a look. I'd be thankful if someone could explain to me why it doesn't work. Thanks in advance !
http://jsfiddle.net/y5mn61qf/
The issue is in your startGame() function, where your pHp and mHp variables are not being set with this.
You have:
pHp = 100;
mHp = 100;
Which should be:
this.pHp = 100;
this.mHp = 100;
I found this by using console.log() which helped me to determine that startGame() was firing, and then upon closer inspection led me to notice that your data was not being updated properly.
In your startGame method you are setting the properties to a new value but forgot this. for the livespan values (pHp, mHp)
I think it should work after adding 'this' before your hp parameters.
startGame: function() {
this.gameIsActive = true;
this.pHp = 100;
this.mHp = 100;
},
Let me start off by saying that this is my second day learning jQuery so I'm very much a beginner.
I've written a document ready function and all components are working except the countryField.change function I wrote. I'm pretty sure the web application already has a change function for this field and I'm not sure if there can be two of the same event on a field. When I say it's not working, I set a breakpoint in the Chrome debugger and it never enters the function.
Maybe I have to temporarily pause the existing event, run my code, then re-enable the default event?
Any help would be appreciated. Thanks.
$(document).ready(function(){
var submitReady = true;
var phoneField = $("p.phone").find("input");
var phoneExt = $("p.Ext").find("input");
var countryField = $("p.country").find("input");
var stateField = $("p.state").find("input");
var provinceField = $("p.Province").find("input");
var regex = /^\([2-9][0-9]{2}\)\s+[2-9][0-9]{2}\-[0-9]{4}$/;
phoneField.mask('(000) 000-0000', {placeholder: "(###) ###-####"});
phoneExt.mask('00000', {placeholder: "#####"});
$('#pardot-form').submit(function() {
// DO STUFF
if (submitReady) {
if (phoneExt.val() != "") {
phoneField.val(phoneField.val() + ' x' + phoneExt.val());
return true;
}
}
else {
return false;
}
});
phoneField.focusout(function() {
if (regex.test($(this).val())) {
submitReady = true;
return true;
}
else {
$(".form-field.phone").after( "<p class='tempError error no-label'>Please Enter a valid phone number: (###) ###-####</p>");
submitReady = false;
}
});
phoneField.focus(function() {
$(".tempError").remove();
});
countryField.change(function() {
phoneField.val("");
provinceField.val("");
stateField.val("");
submitReady = true;
});
});
You can try
$( "p.country" ).change(function() {
phoneField.val("");
provinceField.val("");
stateField.val("");
submitReady = true;
});
Just started with knockout and need to implement page change warning. Following is the code snippet. I just need an alert pop up as warning if any change is made on the page.
function parseViewModel() {
var viewModel = JSON.parse(getState());
viewModel.checking = ko.observable(false);
viewModel.Slider = new ko.observable(100 - viewModel.Slider);
viewModel.CausalsList = buildHierarchy(viewModel.Causals);
viewModel.Causals["-1"] = "Total Marketing Budget";
viewModel.GeographiesList = ko.observableArray(gl);
viewModel.Geographies["0"] = "All Geographies";
viewModel.ProductsList = ko.observableArray(pl);
viewModel.Products["0"] = "All Products";
.
.
.
return viewModel;
}
function bindModel() {
model = parseViewModel();
ko.dirtyFlag = function (root, isInitiallyDirty) {
var result = function () { },
_initialState = ko.observable(ko.toJSON(root)),
_isInitiallyDirty = ko.observable(isInitiallyDirty);
result.isDirty = ko.computed(function () {
return _isInitiallyDirty() || _initialState() !== ko.toJSON(root);
});
result.reset = function () {
_initialState(ko.toJSON(root));
_isInitiallyDirty(false);
};
return result;
};
model.dirtyFlag = new ko.dirtyFlag(model);
model.isDirty.subscribe(function () {
alert("Page change warning!");
});
ko.applyBindings(model, $('#const').get(0));
ko.applyBindings(model, $('#buttonDiv').get(0));
}
Referred Ryan Niemeyer's blog. Unfortunately, it's not working anymore. Any insights please?
You would want to subscribe to model.dirtyFlag.isDirty in your case rather than model.isDirty.
One way to do is by using customBinding. I'm not that familiar with KO either but this might be something you're interested on.
Basically you would do is :-
ko.bindingHandlers.myFunction = {
update : function(){
//do something
}
}
http://knockoutjs.com/documentation/custom-bindings.html
And call it on your element using :-
<h1 data-bind="myFunction:{}"></h1>
Also, a jsfiddle to show how it works. (If you change the value of the First Name and focus out of it then the customBinding gets triggered. )
http://jsfiddle.net/3vuTk
Not sure if it's the best practice though.