Property of an array cannot be read - javascript

I have an extremely complex page that uses dynamic information to generate a layout with the correct and relevant information.
I am storing the data as an object. I have essentially 15 objects with multiple fields of user-submitted data.
Everything is stored and output correctly on the page, however now I am trying to validate and the information when the user tries to edit it from the edit page. The information is all being generated and laid out correctly, however I keep getting the same errors on the validation of the information.
The validation should go through and determine if a field was filled out correctly, and if it was not record a variable and add it to an alert variable. Then once it i done running the validation function it should pop up an alert with what fields still need to be filled in.
I keep receiving an error when it runs through the for loop toward the bottom. It says 'Uncaught TypeError' Cannot read property 'questionNumber' of undefined.
Above the code below I store the object and the properties, but this function is where everything is going awry. Note that there are also 15 arrays in the qtest object, but for the sake of simplification I removed all but a few.
I have gotten this to work on smaller, simpler forms, however because of the complexity and storage method I think this may be missing something or I might not be accessing something correctly. The code is very long and below, I've scaled back as much as possible. Please, if you have any insight or help you can provide I would be extremely grateful. Thank you!
var validateQ = function(qTextID, qAnswerType, TFID, MCID, MCText1, MCText2, MCText3, MCText4, VisRef, Youtube, Vimeo, ImgID) {
if (document.getElementById('ItemName').value == "") {
var quizName = true;
};
if (jQuery('select[name="CAT_Custom_14"]').val() == 'Quiz') {
if (jQuery(qTextID).val() == "") {
var qText = true;
};
if (jQuery('CAT_Custom_249').val() == " ") {
var quizscore1 = true;
};
if (jQuery(qAnswerType).val() == " ") {
var answertype = true;
} else if (jQuery(qAnswerType).val() == 'True/False') {
if (!jQuery(TFID).is(':checked')) {
var tfanswer = true;
var mcanswer = false;
};
} else if (jQuery(qAnswerType).val() == 'Multiple Choice') {
if (!jQuery(MCID).is(':checked')) {
var mcanswer = true;
var tfanswer = false;
};
if (jQuery(MCText1).val() == "" || jQuery(MCText2).val() == "" || jQuery(MCText3).val() == "" || jQuery(MCText4).val() == "") {
var mcTextfields = true;
} else {
mcTextfields = false;
};
};
} else if (jQuery('select[name="CAT_Custom_14"]').val() == 'Survey') {
if (jQuery(qTextID).val() == "") {
var qText = true;
};
if (!jQuery(sAnswers1).is(':checked')) {
var surveyAnswers1 = true;
} else {
surveyAnswers1 = false;
};
};
if (jQuery(VisRef).val() != " ") {
if (jQuery(VisRef).val() == "Youtube Video" && jQuery(Youtube).val() == "") {
var youtubeVal = true;
} else if (jQuery(VisRef).val() == "Vimeo Video" && jQuery(Vimeo).val() == "") {
var vimeoVal = true;
} else {
// validateImage(ImgID);
};
} else {
youtubeVal = false;
vimeoVal = false;
var tempImgCheck = false;
};
if (numCheck == 15) {
numCheck = 16;
};
var qName = "- Quiz or Survey Name\n";
var shortDescription = "- A short description of the Quiz/Survey\n";
var scoreMessage = "- A required passing score\n";
var QTextMessage = "- Question text\n";
var answerTMessage = "- An answer type\n";
var mcFields = "- The Multiple Choice answer fields\n";
var mcMessage = "- The correct Multiple Choice Answer\n"
var tfMessage = "- The correct True/False answer\n";
var vimMessage = "- A Vimeo Video code\n";
var ytMessage = "- A Youtube Video code\n";
var imgMessage = "- A reference image\n";
var surveyMessage = "- An answer type\n";
if (quizName == true || quizscore1 == true || qText == true || answertype == true || tfanswer == true || mcanswer == true || mcTextfields == true || youtubeVal == true || vimeoVal == true || tempImgCheck == true || surveyAnswers1 == true) {
var alertText = "It appears that you have not finished completing question" + question[i].questionNumber + ". Please ensure that you have completed the following question fields.\n";
if (quizName == true) {
alertText = alertText + qName;
};
if (quizscore1 == true) {
alertText = alertText + scoreMessage;
};
if (qText == true) {
alertText = alertText + QTextMessage;
};
if (answertype == true) {
alertText = alertText + answerTMessage;
};
if (tfanswer == true) {
alertText = alertText + tfMessage;
};
if (mcanswer == true) {
alertText = alertText + mcMessage;
};
if (mcTextfields == true) {
alertText = alertText + mcFields;
};
if (youtubeVal == true) {
alertText = alertText + ytMessage;
};
if (vimeoVal == true) {
alertText = alertText + vimMessage;
};
if (tempImgCheck == true) {
alertText = alertText + imgMessage;
};
if (surveyAnswers1 == true) {
alertText = alertText + surveyMessage;
};
if (quizscore1 == true) {
alertText = alertText + scoreMessage;
};
confirm(alertText);
};
};
var numCheck = 1;
var checkQuizQ = function() {
for (j = 1; j<= qtest.length; j++) {
numCheck = numCheck + 1;
if (qtest[j].questionNumber == "1") {
validateQ("CAT_Custom_3", "CAT_Custom_8", "CAT_Custom_19", "CAT_Custom_18", "CAT_Custom_4", "CAT_Custom_5", "CAT_Custom_6", "CAT_Custom_7", "CAT_Custom_9", "CAT_Custom_10", "CAT_Custom_11", "CAT_Custom_12", "CAT_Custom_230");
} else if (qtest[j].questionNumber == "2") {
validateQ("CAT_Custom_20", "CAT_Custom_21", "CAT_Custom_29", "CAT_Custom_26", "CAT_Custom_22", "CAT_Custom_23", "CAT_Custom_24", "CAT_Custom_25", "CAT_Custom_30", "CAT_Custom_31", "CAT_Custom_32", "CAT_Custom_33", "CAT_Custom_231");
} else if (qtest[j].questionNumber == "3") {
validateQ("CAT_Custom_35", "CAT_Custom_36", "CAT_Custom_37", "CAT_Custom_40", "CAT_Custom_41", "CAT_Custom_42", "CAT_Custom_43", "CAT_Custom_44", "CAT_Custom_45", "CAT_Custom_46", "CAT_Custom_47", "CAT_Custom_48", "CAT_Custom_232");
} else if (qtest[j].questionNumber == "4") {
};
};
document.getElementById('catcustomcontentbutton').style.display = "block";
document.getElementById("qsValidate").style.display = "none";
};

Since qtest looks like an array, its index starts from 0 to length - 1 so when j is length the value of qtest[j] will be undefined.
So change the loop as
for (j = 0; j< qtest.length; j++) {
//
}

Related

How to check if the selected value of drop-down is set to No and Text-Box is blank using JavaScript

I have drop-down and text-box in a gridview and I am trying to check if the selected value of a drop-down is set to "No" and no comments is entered in the text-box then i want to show message. The requirement should be as long as the selected value of the drop down is set to No then comments must be entered in the text-box. My issue is that i am getting the message even if the drop-down is set to Yes or comments is provided when the drop down is set to No. Here is the code:
function validate() {
var flag = false;
var gridView = document.getElementById('<%= GridView1.ClientID %>');
for (var i = 1; i < gridView.rows.length; i++) {
var ddl = gridView.rows[i].getElementsByTagName('Select');
var areas = gridView.rows[i].getElementsByTagName('textarea');
if (ddl != null && ddl.length > 1 && ddl[0] != null && areas != null && areas.length > 1 && areas[0] != null) {
if (areas[0].type == "textarea" && ddl[0].type == "select-one") {
var txtval = areas[0].value;
var txtddl = ddl[0].value;
if (txtddl.value == "No" && (txtval == "" || txtval == null)) {
flag = false;
break;
}
else {
flag = true
}
}
}
}
if (!flag) {
alert('Please note that comments is required if drop down is set to No. Thanks');
areas[i].focus();
}
return flag;
}
</script>
You can do like this:
<script>
function validate() {
var flag = false;
var gridView = document.getElementById('<%= GridView1.ClientID %>');
for (var i = 1; i < gridView.rows.length; i++) {
var selects = gridView.rows[i].getElementsByTagName('select');
//var inputs = gridView.rows[i].getElementsByTagName('input');
var areas = gridView.rows[i].getElementsByTagName('textarea');
if (selects != null && areas != null) {
if (areas[0].type == "textarea") {
var txtval = areas[0].value;
var selectval = selects[0].value;
if (selectval == "No" && (txtval == "" || txtval == null)) {
flag = false;
break;
}
else {
flag = true;
}
}
}
}
if (!flag) {
alert('Please enter comments. Thanks');
}
return flag;
}
</script>
Try this:
$('#select').on('change', function () {
var text = $(this).find(":selected").text();
var textBox = $(this).parent().filter('input [name="InputName"]');
if(text == "no" && textBox.val() =="")
{
\\display your message
}
});

Javascript Expandable Header not working correctly

I am using a piece of Javascript that enables the user to expand a h3 tag in my HTML document. It is working perfectly however when I refresh my page the first time the header is contracted and then when I refresh it a second time the header is expanded again.
I would like it to just stay expanded and not contract ever but I am unsure what changes I may need to make to the code:
I should point out that when the user visits the page for the first time the header is already expanded. I do that by calling the function from within the body tag.
<body onLoad="expandcontent('sc1')">
This is the code:
var enablepersist = "on" //Enable saving state of content structure using session cookies? (on/off)
var collapseprevious = "yes" //Collapse previously open content when opening present? (yes/no)
if (document.getElementById) {
document.write('<style type="text/css">')
document.write('.switchcontent{display:none;}')
document.write('</style>')
}
function getElementbyClass(classname) {
ccollect = new Array()
var inc = 0
var alltags = document.all ? document.all : document.getElementsByTagName("*")
for (i = 0; i < alltags.length; i++) {
if (alltags[i].className == classname)
ccollect[inc++] = alltags[i]
}
}
function contractcontent(omit) {
var inc = 0
while (ccollect[inc]) {
if (ccollect[inc].id != omit)
ccollect[inc].style.display = "none"
inc++
}
}
function expandcontent(cid) {
if (typeof ccollect != "undefined") {
if (collapseprevious == "yes")
contractcontent(cid)
document.getElementById(cid).style.display = (document.getElementById(cid).style.display != "block") ? "block" : "none"
}
}
function revivecontent() {
contractcontent("omitnothing")
selectedItem = getselectedItem()
selectedComponents = selectedItem.split("|")
for (i = 0; i < selectedComponents.length - 1; i++)
document.getElementById(selectedComponents[i]).style.display = "block"
}
function get_cookie(Name) {
var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) {
offset += search.length
end = document.cookie.indexOf(";", offset);
if (end == -1) end = document.cookie.length;
returnvalue = unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}
function getselectedItem() {
if (get_cookie(window.location.pathname) != "") {
selectedItem = get_cookie(window.location.pathname)
return selectedItem
} else
return ""
}
function saveswitchstate() {
var inc = 0,
selectedItem = ""
while (ccollect[inc]) {
if (ccollect[inc].style.display == "block")
selectedItem += ccollect[inc].id + "|"
inc++
}
document.cookie = window.location.pathname + "=" + selectedItem
}
function do_onload() {
uniqueidn = window.location.pathname + "firsttimeload"
getElementbyClass("switchcontent")
if (enablepersist == "on" && typeof ccollect != "undefined") {
document.cookie = (get_cookie(uniqueidn) == "") ? uniqueidn + "=1" : uniqueidn + "=0"
firsttimeload = (get_cookie(uniqueidn) == 1) ? 1 : 0 //check if this is 1st page load
if (!firsttimeload)
revivecontent()
}
}
if (window.addEventListener)
window.addEventListener("load", do_onload, false)
else if (window.attachEvent)
window.attachEvent("onload", do_onload)
else if (document.getElementById)
window.onload = do_onload
if (enablepersist == "on" && document.getElementById)
window.onunload = saveswitchstate

Ensuring that an entered name doesn’t end with a space

I am trying to get it so that if I type in a name that ends with a space, the textfield will go red. Most of the code works its just one method does not seem to be working.
The issue must be somewhere in the last index part?
var NamePass = true;
function ValidateName() {
var BlankPass = true;
var GreaterThan6Pass = true;
var FirstBlankPass = true;
var BlankMiddleName = true;
if (document.getElementById('Name').value == "") {
BlankPass = false;
}
var Size = document.getElementById('Name').value.length;
console.log("Size = " + Size);
if (Size < 7) {
GreaterThan6Pass = false;
}
if (document.getElementById('Name').value.substring(0, 1) == " ") {
FirstBlankPass = false;
}
var LastIndex = document.getElementById('Name').value.lastIndexOf();
if (document.getElementById('Name').value.substring((LastIndex - 1), 1) == " ") {
FirstBlankPass = false;
}
string = document.getElementById('Name').value;
chars = string.split(' ');
if (chars.length > 1) {} else
BlankMiddleName = false;
if (BlankPass == false || GreaterThan6Pass == false || FirstBlankPass == false || BlankMiddleName == false) {
console.log("BlankPass = " + BlankPass);
console.log("GreaterThan6Pass = " + GreaterThan6Pass);
console.log("FirstBlankPass = " + FirstBlankPass);
console.log("BlankMiddleName = " + BlankMiddleName);
NamePass = false;
document.getElementById('Name').style.background = "red";
} else {
document.getElementById('Name').style.background = "white";
}
}
http://jsfiddle.net/UTtxA/10/
lastIndexOf gets the last index of a character, not the last index in a string. I think you meant to use length instead:
var lastIndex = document.getElementById('Name').value.length;
Another problem with that, though, is that substring takes a start and end index, not a start index and a substring length. You could use substr instead, but charAt is easier:
if (document.getElementById('Name').value.charAt(lastIndex - 1) == " ") {
FirstBlankPass = false;
}
Now, for some general code improvement. Instead of starting with all your variables at true and conditionally setting them to false, just set them to the condition:
var NamePass = true;
function ValidateName() {
var value = document.getElementById('Name').value;
var BlankPass = value == "";
var GreaterThan6Pass = value.length > 6;
var FirstBlankPass = value.charAt(0) == " ";
var LastBlankPass = value.charAt(value.length - 1) == " ";
var BlankMiddleName = value.split(" ").length <= 1;
if (BlankPass || GreaterThan6Pass || FirstBlankPass || LastBlankPass || BlankMiddleName) {
console.log("BlankPass = " + BlankPass);
console.log("GreaterThan6Pass = " + GreaterThan6Pass);
console.log("FirstBlankPass = " + FirstBlankPass);
console.log("BlankMiddleName = " + BlankMiddleName);
NamePass = false;
document.getElementById('Name').style.background = "red";
} else {
document.getElementById('Name').style.background = "white";
}
}
A couple more points of note:
It’s probably a good idea to use camelCase variable names instead of PascalCase ones, the latter usually being reserved for constructors
blah == false should really be written as !blah
An empty if followed by an else can also be replaced with if (!someCondition)
That function looks like it should return true or false, not set the global variable NamePass
Penultimately, you can sum this all up in one regular expression, but if you intend to provide more specific error messages to the user based on what’s actually wrong, then I wouldn’t do that.
function validateName() {
return /^(?=.{6})(\S+(\s|$)){2,}$/.test(document.getElementById('name').value);
}
And finally — please keep in mind that not everyone has a middle name, or even a name longer than 6 characters, as #poke points out.

javascript form cookies - select only opening cookie for first 10 indexes

I have never used cookies before, so I am using a peice of code I am very unfamiliar with.
It was working all fine, until I noticed just now that for select boxes, it is not working for any values after the tenth index. (for index 10 and above).
I have looked at the cookie stored on my system, and it appears t be saving them correctly. (I saw select10) ETC stored properly.
When it runs onload of body however, it is not loading in the values properly.
Here is the cookie code I am using:
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
var expDays = 100;
var exp = new Date();
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));
function getCookieVal (offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1) { endstr = document.cookie.length; }
return unescape(document.cookie.substring(offset, endstr));
}
function GetCookie (name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg) return getCookieVal (j);
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function SetCookie (name, value) {
var argv = SetCookie.arguments;
var argc = SetCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
var path = (argc > 3) ? argv[3] : null;
var domain = (argc > 4) ? argv[4] : null;
var secure = (argc > 5) ? argv[5] : false;
document.cookie = name + "=" + escape (value) +
((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
((path == null) ? "" : ("; path=" + path)) +
((domain == null) ? "" : ("; domain=" + domain)) +
((secure == true) ? "; secure" : "");
}
// use the following code to call it:
// <body onLoad="cookieForms('open', 'form_1', 'form_2', 'form_n')" onUnLoad="cookieForms('save', 'form_1', 'form_2', 'form_n')">
function cookieForms() {
var mode = cookieForms.arguments[0];
for(f=1; f<cookieForms.arguments.length; f++) {
formName = cookieForms.arguments[f];
if(mode == 'open') {
cookieValue = GetCookie('saved_'+formName);
if(cookieValue != null) {
var cookieArray = cookieValue.split('#cf#');
if(cookieArray.length == document[formName].elements.length) {
for(i=0; i<document[formName].elements.length; i++) {
if(cookieArray[i].substring(0,6) == 'select') { document[formName].elements[i].options.selectedIndex = cookieArray[i].substring(7, cookieArray[i].length-1); }
else if((cookieArray[i] == 'cbtrue') || (cookieArray[i] == 'rbtrue')) { document[formName].elements[i].checked = true; }
else if((cookieArray[i] == 'cbfalse') || (cookieArray[i] == 'rbfalse')) { document[formName].elements[i].checked = false; }
else { document[formName].elements[i].value = (cookieArray[i]) ? cookieArray[i] : ''; }
}
}
}
}
if(mode == 'save') {
cookieValue = '';
for(i=0; i<document[formName].elements.length; i++) {
fieldType = document[formName].elements[i].type;
if(fieldType == 'password') { passValue = ''; }
else if(fieldType == 'checkbox') { passValue = 'cb'+document[formName].elements[i].checked; }
else if(fieldType == 'radio') { passValue = 'rb'+document[formName].elements[i].checked; }
else if(fieldType == 'select-one') { passValue = 'select'+document[formName].elements[i].options.selectedIndex; }
else { passValue = document[formName].elements[i].value; }
cookieValue = cookieValue + passValue + '#cf#';
}
cookieValue = cookieValue.substring(0, cookieValue.length-4); // Remove last delimiter
SetCookie('saved_'+formName, cookieValue, exp);
}
}
}
// End -->
</script>
I beleive the problem lies with the following line, found about 3/4 of the way down the code block above (line 68):
if(cookieArray[i].substring(0,6) == 'select') { document[formName].elements[i].options.selectedIndex = cookieArray[i].substring(7, cookieArray[i].length-1); }
Just for reference, here is the opening body tag I am using:
<body style="text-align:center;" onload="cookieForms('open', 'ramsform', 'decksform', 'hullsform', 'crewform', 'shipwrightform'); Swap(crew0z,'crew0i'); Swap(crew1z,'crew1i'); Swap(crew2z,'crew2i'); Swap(crew3z,'crew3i'); Swap(crew4z,'crew4i'); Swap(crew5z,'crew5i'); Swap(crew6z,'crew6i'); Swap(crew7z,'crew7i'); Swap(crew8z,'crew8i'); Swap(crew9z,'crew9i');" onunload="cookieForms('save', 'ramsform', 'decksform', 'hullsform', 'crewform', 'shipwrightform');">
(Please ignore the swap()'s as they are unrelated)
Page I am working on can be found: http://webhostlet.com/POP.htm
In both the open and save codes, change:
document[formName].elements[i].options.selectedIndex
to:
document[formName].elements[i].selectedIndex
options is an array of all the options, the selectedIndex property belongs to the select element that contains them.
Change:
cookieArray[i].substring(7, cookieArray[i].length-1)
to:
cookieArray[i].substring(6)
You were off by 1 because you forgot that it's 0-based counting. The second argument isn't needed, it defaults to the rest of the string.
The reason it worked for the first 10 menu items is a quirk of substring: if the second argument is lower than the first, it swaps them! So "select5".substring(7, 6) is treated as "select5".substring(6, 7), which gets the last character of the string. But for the longer strings, it was `"select35".substring(7, 7), which is an empty string.

Why will my Javascript not run in IE

Below is my code. It is supposed to filter a table. It functions great in everything but IE. Can you help?
Perhaps there is a missing tag or something. I've been over it a number of times and could really do with someone's help please!
<script type="text/javascript">
function hasPath(element, cls) {
return (' ' + element.getAttribute('pathway')).indexOf(cls) > -1;
}
function hasLevel(element, cls) {
return (' ' + element.getAttribute('level')).indexOf(cls) > -1;
}
function hasBody(element, cls) {
return (' ' + element.getAttribute('body')).indexOf(cls) > -1;
}
function QualificationSearch() {
var imgdiv = document.getElementById("Chosen_Pathway_img");
var p = document.getElementById("PathwaySelect");
var pathway = p.options[p.selectedIndex].value;
if (pathway == "ALLPATHS") {
pathway = "";
imgdiv.src = "/templates/superb/images/QualChecker/pic_0.png"
}
if (pathway == "ES") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_1.png"
}
if (pathway == "HOUSING") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_2.png"
}
if (pathway == "PLAYWORK") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_3.png"
}
if (pathway == "SC") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_4.png"
}
if (pathway == "YW") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_5.png"
}
var a = document.getElementById("AwardingBodySelect");
var awardingBody = a.options[a.selectedIndex].value;
if (awardingBody == "ALLBODIES") {
awardingBody = "";
}
var levelGroup = document.getElementsByName("LevelGroup");
var chosenLevel = ""
for (var g = 0; g < levelGroup.length; g++) {
if (levelGroup[g].checked) {
chosenLevel += levelGroup[g].value + " ";
}
}
if (chosenLevel == undefined) {
var chosenLevel = "";
} else {
var splitLevel = chosenLevel.split(" ");
var levelA = splitLevel[0];
var levelB = splitLevel[1];
var levelC = splitLevel[2];
var levelD = splitLevel[3];
if (levelA == "") {
levelA = "NOLVL"
}
if (levelB == "") {
levelB = "NOLVL"
}
if (levelC == "") {
levelC = "NOLVL"
}
if (levelD == "") {
levelD = "NOLVL"
}
}
var fil = document.getElementsByName("QList");
for (var i = 0; i < fil.length; i++) {
fil.item(i).style.display = "none";
if ((hasBody(fil.item(i), awardingBody) == true || awardingBody == "") && (hasPath(fil.item(i), pathway) == true || pathway == "") && ((hasLevel(fil.item(i), levelA) == true || hasLevel(fil.item(i), levelB) == true || hasLevel(fil.item(i), levelC) == true || hasLevel(fil.item(i), levelD) == true) || chosenLevel == "")) {
fil.item(i).style.display = "block";
}
}
}
</script>
Check your semicolons. IE is far more strict on that kind of stuff than FF.

Categories