Function code after for loop doesn't get executed ever - javascript

I'm trying to create a registration form and validate input fields using javascript, but I'm having difficulties after the for loop executes...
function checkValidation1() {
var elem = document.getElementsByTagName("input");
for(var i = 0; i < elem.length; i++) {
if($("#"+elem[i].id).val()=="") {
$("#"+elem[i].id+"error").html("<img src='images/exclamationsmall.png' title='"+elem[i].name+" should not be blank'>");
} else if(elem[i].name=="email") {
var emailReg = /^([_a-zA-Z0-9-]+)(\.[_a-zA-Z0-9-]+)*#([a-zA-Z0-9-]+\.)+([a-zA-Z]{2,3})$/;
if(!emailReg.test($("#"+elem[i].id).val())) {
$("#"+elem[i].id+"error").html("<img src='images/exclamationsmall.png' title='"+elem[i].name+" is invalid'>");
}
} else {
$("#"+elem[i].id+"error").html("");
}
}
alert("fasfasfasfasfasf");
}
The alert doesn't execute for some reason. Any ideas?

Verify that all of your input elements actually have an id attribute. Otherwise this line:
if ($("#" + elem[i].id).val() == "") {
...will result in an expression containing only an octothorpe -- $("#") -- and the following error:
Syntax error, unrecognized expression: #
...which ultimately prevents the code from reaching the alert.

Related

issues with javascript checkboxes issues

the following code just says unexpected identifier;
var icheckBoxes = $('input[type="checkbox"]');
for(int i=0; i < icheckBoxes.length; i++) {
if (!icheckBoxes[i].is(":checked")) {
$('input[type="checkbox').addClass('has-error');
AgreeIsActive = false;
$('#AgreementSubmit').prop('disabled', false);
return;
}
}
Seems to be the int as the culprit but i tried it to change it to var but no success and got a different error:
Uncaught TypeError: icheckBoxes[i].is is not a function
Update#1
New Code added with the help
var icheckBoxes = $('input[type="checkbox"]');
alert(icheckBoxes.length);
for(var i=0; i < icheckBoxes.length; i++) {
alert(i);
//if (!icheckBoxes[i].is(":checked")) {
if(!icheckBoxes.eq(i).is(":checked")) {
alert(i);
$('input[type="checkbox').addClass('has-error');
AgreeIsActive = false;
$('#AgreementSubmit').prop('disabled', false);
return;
}
}
it says the length is 4 and then it goes inside and it alerts 4 times 0 and the next alert which is inside the if condition, it just alerts it 1 time and that is also 0
icheckBoxes[i].is(":checked")
should be
icheckBoxes.eq(i).is(":checked")
[] breaks the element out of the jQuery object and is() is a jQuery method.
Also as a side note, $('input[type="checkbox') is missing the "] on the end of it to make it a valid selector.

Cannot read attribute of null using array

I am trying to change the the classes of element that already exist but are hidden . This problem is whenever the code is executed a null exception is thrown. Tried everything but can't seem to get what's wrong
function changeMenu(code) {
var i, id = ["'demo'", "'drill'", "'alert'"];
for (i = 0; i <= 2; i += 1) {
if (document.getElementById(id[i]) !== null) {
if (i !== code) {
document.getElementById(id[i]).setAttribute('class', 'row hidden');
} else {
document.getElementById(id[i]).setAttribute('class', 'row');
}
} else {window.alert("error");}
}
}
The script is already loaded in the end of document and the id also exists.
The problem here is that you are storing the ids with the ' in your strings, so when you will call document.getElementById("'demo'") it won't find the element and return null.
Change your id array declaration to:
var i, id = ["demo", "drill", "alert"];
The script is already loaded in the end of document and the id also exists.
Yes the id exists but they don't have ' on it, just remove it from your array.
There are several issues with quotes and tests
I believe you actually meant to do this:
var ids = ["demo", "drill", "alert"];
function changeMenu(code) {
for (var i = 0; i < ids.length; i++) {
var elm = document.getElementById(id[i]);
if (elm) { // element exists
elm.classList.toggle("hidden",ids[i] !== code);
}
else {
window.alert("error");
}
}
}

Calling the filter method on a JQuery object is not working when done inside of a function

My knowledge of jQuery and more specifically javascript has always been very limited and I am working hard to get better.
With that in mind I am trying to create some sort of "extensible validation framework" in that I can create an object with a validation function and its error message, push it into an array and then call all those methods and report the messages from the ones that fail.
So first I did something very simple just to see that the basic validation worked which was this:
var selectedTourDate = $("#tourDate").val();
var list = $("#bookedTourDate *");
var isDateBooked = list.filter(function () {
return (this.innerHTML == selectedTourDate) ;
}).length !== 0;
if (isDateBooked) {
alert("Date invalid");
return;
}
This works fine.
Then I created my "framework" which is this:
function Validator(fn, errorMessage) {
this.validationFunction = fn;
this.errorMessage = errorMessage;
};
var validationRunner = {
validators: [],
errorMessages: [],
validationResult: true,
addValidation: function (validator) {
validationRunner.validators.push(validator);
},
validate: function () {
for (var validator = 0; validator < validationRunner.validators.length; validator++) {
if (validationRunner.validators[validator] instanceof Validator) {
var result = validationRunner.validators[validator].validationFunction();
validationResult = validationRunner.validationResult && result;
if (!result)
validationRunner.errorMessages.push(validationRunner.validators[validator].errorMessage);
}
}
},
getErrorMessage: function () {
var message = "<ul>";
for (var errorMessage = 0; errorMessage > validationRunner.errorMessages.length; errorMessage++) {
message += "<li>" + errorMessage + "</li>";
}
message += "</ul>";
return message;
}
}
And then modified the first block of code as follows:
var selectedTourDate = $("#tourDate").val();
var list = $("#bookedTourDate *");
var tmp = new Validator(function () {
return list.filter(function () {
return (this.innerHTML == selectedTourDate);
}).length !== 0;
}, "Date already booked");
validationRunner.addValidation(tmp);
validationRunner.validate();
var msg = validationRunner.getErrorMessage();
This does not work at all.
It seems that the problem is that in this statement:
return (this.innerHTML == selectedTourDate);
The "this" is the Validator object instead of the html element from the list which confuses me since as its inside the function of the "filter" method it should be.
Is there a way to correct this so I can accomplish what I am trying to do here?
this does have the correct value but there are some mistakes in the getErrorMessage function.
To check the value of this don't rely on a debugger's "watch variable" function but do a console.log which will give you the value at a specific point of the code execution.
My changes:
for (var errorMessage = 0; errorMessage < validationRunner.errorMessages.length; errorMessage++) {
message += "<li>" + validationRunner.errorMessages[errorMessage] + "</li>";
}
The errorMessage variable is only a index and not the actual error message. Also you used a "bigger than" instead of a "smaller than" sign.
Here's a fiddle
That is very odd, as this should be the current DOM element per jquery api.
The function should take an index as a parameter, though. So what about trying
return list.filter(function (i) {
return (list.get(i).innerHTML == selectedTourDate);
}).length !== 0;

Get error message of page validators for particular group by javascript in asp.net

I am trying to write javascript function in which I want to show the error message of the of the invalid fields of the validatiors whose groupname is given.
Basically I am having some different group of validators and want to show there error message in alert if value entered is in valid for the group whose button is pressed using common function.
I am using following code:
function check(group) {
if (Page_ClientValidate(group)) {
return true;
}
else {
var message="";
for (i = 0; i < Page_Validators.length; i++) {
if (!Page_Validators[i].isValid) {
message = message + Page_Validators[i].Errormessage+ "\n";
}
}
alert("Enter following fields marked with * or Invalid Data\n"+message);
return false;
}
I want to run following section of code for particular group of validators:
var message="";
for (i = 0; i < Page_Validators.length; i++) {
if (!Page_Validators[i].isValid) {
message = message + Page_Validators[i].Errormessage+ "\n";
}
}
alert("Enter following fields marked with * or Invalid Data\n"+message);
return false;
}
If i understood correctly, a simple switch statement would do the trick
for (i = 0; i < Page_Validators.length; i++) {
switch(Page_Validators[i].validationGroup)
{
case "MyGroup1":
// your javascript code
break;
case "MyGroup2":
// your javascript code
break;
default:
// your javascript code
break;
}
}
If you need to see the javascript object properties, set a breakpoint in the javascript and debug using Visual Studio

Javascript e-mail validation of specific domains

I can’t figure out what is missing so that when e-mail is valid it will skip the last invalid message and move to next item on form for validation:
enter code here
if (document.form1.email.value.length > 0) {
var tst = document.form1.email.value;
var okd = ['bankofamerica.com','baml.com','magner.com','ml.com','ust.com','ustrust.com']
for (var i = 0; i < okd.length; i++) { okd[i] == okd[i].toLowerCase() }
var emailRE = /^[a-zA-Z0-9._+-]+#([a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})$/
var aLst = emailRE.exec(tst)
if (!aLst) {
alert(tst + ' is not a valid e-mail')
} else {
var sLst = aLst[1].toLowerCase()
for (var i = 0; i < okd.length; i++) {
if (sLst == okd[i]) {
// alert(aLst[1] + ' is allowed');-->
}
}
if (i == okd.length) alert(aLst[1] + ' is not allowed. Please enter an email address with an authorized domain.')
document.form1.email.select();
return false;
}
}
I'd recommend placing this code into a function, maybe named ValidateEmail().
In your loop: if you've determined the email is valid, return true;. This will prevent further execution. If that domain doesn't match, have it continue looping to check the others.
If the loop completes without returning true, you'll know it didn't match anything so return false; at the very end.
EDIT: Use try/catch instead:
if (document.form1.email.value.length > 0) {
var tst = document.form1.email.value;
var okd = ['bankofamerica.com','baml.com','magner.com','ml.com','ust.com','ustrust.com']
for (var i = 0; i < okd.length; i++) { okd[i] == okd[i].toLowerCase() }
try {
var emailRE = /^[a-zA-Z0-9._+-]+#([a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})$/
var aLst = emailRE.exec(tst)
if (!aLst)
throw (tst + ' is not a valid e-mail');
// isValidDomain will be changed to 'true' only if it matches an item in the array
var isValidDomain = false;
var sLst = aLst[1].toLowerCase()
for (var i = 0; i < okd.length; i++) {
if (sLst == okd[i]) {
isValidDomain = true;
// We break here because a match has been found - no need to compare against the other domain names.
break;
}
}
if(!isValidDomain)
throw (aLst[1] + ' is not allowed. Please enter an email address with an authorized domain.');
// If execution reaches here, you know it passed both tests!
return true;
}
catch(err) {
// This code block runs whenever an error occurs
alert(err);
document.form1.email.select();
return false;
}
}
throw basically acts like a goto command. It will jump directly to the catch(err) portion of the code.
More info about try, catch, and throw:
http://www.w3schools.com/js/js_try_catch.asp
http://www.w3schools.com/js/js_throw.asp
Thank you very much Colin!
I had to remove the following 2 lines to avoid halting the code from running on to next validation field:
isValidDomain = true;
// We break here because a match has been found - no need to compare against the other domain names.
// break - exits code from running on down to next item on page
}
}
if (!isValidDomain)
throw (aLst[1] + ' is not allowed. Please enter an email address with an authorized domain.');
// If execution reaches here, you know it passed both tests!
// return true; - was not needed, stops code from running on page
}
catch (err) {

Categories

Resources