Firefox javascript error function "undefined" works fine in IE - javascript

I'm receiving an error in firefox error console "Error: submitSearchForm is not defined"
this is my code for that function
EDIT: added full code
function submitSearchForm(action,iskeyDown) {
var oneEntered = false;
if(iskeyDown == null || iskeyDown == 'undefined'){
copyAndValidate("dobFrom", "searchCriteria.dob", "date");
copyAndValidate("dobTo", "searchCriteria.dobTo", "date");
copyAndValidate("dodFrom", "searchCriteria.dodFrom", "date");
copyAndValidate("dodTo", "searchCriteria.dodTo", "date");
copyAndValidate("searchCriteria.age", "searchCriteria.age", "integer");
}else{
copyAndValidate("dobFrom_date", "searchCriteria.dob", "date");
copyAndValidate("dobTo_date", "searchCriteria.dobTo", "date");
copyAndValidate("dodFrom_date", "searchCriteria.dodFrom", "date");
copyAndValidate("dodTo_date", "searchCriteria.dodTo", "date");
copyAndValidate("searchCriteria.age", "searchCriteria.age", "integer");
}
var elements = document.SearchForm.getElementsByTagName("INPUT");
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element != null && element.getAttribute("group") == 'searchCriteria') {
if (!isEmpty(element.value)) {
oneEntered = true;
break;
}
}
}
if (oneEntered)
{
if (validate(document.SearchForm)) {
document.SearchForm.action.value = action;
document.SearchForm.submit();
}
}
else {
alert("<%= bpt.getValue("CCT_ATLEASTONE_MSG") %>");
}
}
button
onclick="<%="submitSearchForm('"+SearchForm.ACTION_SEARCH +"');"%>"
just to say again everything works fine in IE so the code is correct
EDIT: VALIDATION.JS validate()
function validate(thisForm) {
window.event.returnValue = false;
formToValidate = thisForm;
var ret = true;
var validationErrors = new Array();
// get the validateable items
// var validateThese = getValidationItems(thisForm.childNodes);
var validateThese = getValidationItems(thisForm);
//printValidationArray(validateThese);
// validate them
for (var i = 0; i < validateThese.length; i++) {
var validationItem = validateThese[i];
var validationError = validateMe(validationItem);
if (validationError != "") {
validationErrors[validationErrors.length] = validationError;
}
}
// check for validation errors
if (validationErrors.length > 0) {
var errors = "";
for (var j = 0; j < validationErrors.length; j++) {
errors += validationErrors[j] + "\n";
}
alert("Validation Errors:\n" + errors);
ret = false;
} else {
ret = true;
}
return ret;
}

window.event (also referenced as just event) is not a standard global object in JavaScript. It is an IE-only "feature."
See this question.
Try changing the function declaration to:
function submitSearchForm(action, iskeyDown) {
// ...
// { <------------------------------------------------ brace removed
if (validate(document.SearchForm)) {
document.SearchForm.action.value = action;
document.SearchForm.submit();
}
// } <----------------------------------------------- brace removed
}
Braces in JavaScript do not work the same way as in, say, Java. Depending on where they are placed, they mean different things. Example: this question.
I'm guessing the syntax error in the submitSearchForm function declaration is the source of your problem.
I'm still not sure that the code you've posted is actually the code the browser sees, but if so, try this:
function submitSearchForm(action, iskeyDown) {
var oneEntered = false;
if (iskeyDown === null || typeof iskeyDown === 'undefined') {
copyAndValidate("dobFrom", "searchCriteria.dob", "date");
copyAndValidate("dobTo", "searchCriteria.dobTo", "date");
copyAndValidate("dodFrom", "searchCriteria.dodFrom", "date");
copyAndValidate("dodTo", "searchCriteria.dodTo", "date");
copyAndValidate("searchCriteria.age", "searchCriteria.age", "integer");
} else {
copyAndValidate("dobFrom_date", "searchCriteria.dob", "date");
copyAndValidate("dobTo_date", "searchCriteria.dobTo", "date");
copyAndValidate("dodFrom_date", "searchCriteria.dodFrom", "date");
copyAndValidate("dodTo_date", "searchCriteria.dodTo", "date");
copyAndValidate("searchCriteria.age", "searchCriteria.age", "integer");
}
var elements = document.SearchForm.getElementsByTagName("INPUT");
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element !== null && element.getAttribute("group") === 'searchCriteria') {
if (!isEmpty(element.value)) {
oneEntered = true;
break;
}
}
}
if (oneEntered)
{
if (validate(document.SearchForm)) {
document.SearchForm.action.value = action;
document.SearchForm.submit();
}
}
else {
alert('<%= bpt.getValue("CCT_ATLEASTONE_MSG") %>');
}
}

window.event is IE's specific, take a look here for (a bit old) table for different browsers:
http://www.javascriptkit.com/domref/domevent.shtml
Here's the official documentation:
https://developer.mozilla.org/en/DOM/Event
Here's another post for that:
http://www.sitepoint.com/forums/showthread.php?t=330837

I had similar error just resolved the same.
The form tag should be under <html><body> tag. e.g. <html><body><form></form></body></html>
If you have just used <form></form> tag and trying to submit then it gives error in older version of mozill while it works in newer version and other browsers.

Related

Angular - multiselect-dropdown - TypeError: Cannot read property 'length' of undefined

counter: number = 0;
getDatatypes(){
if(this.counter == 0) {
if(this.appId != 0)
{
if(undefined != this.datatypes && this.datatypes.length)
for (let i = 0; i < this.datatypes.length; i++) {
this.applicationDataType = new ApplicationDataType(this.route.snapshot.params.id, this.datatypes[i].dataTypeId, this.datatypes[i].description, false);
let datatype = this.checkedDatatypes.find(y => y.description === this.datatypes[i].description);
if (datatype) {
this.applicationDataType.checked = true;
this.applicationDataTypes.push(this.applicationDataType);
} else {
this.applicationDataType.checked = false;
this.applicationDataTypes.push(this.applicationDataType);
}
}
} else {
for(let i = 0; i < this.datatypes.length; i++){
this.applicationDataType = new ApplicationDataType(this.route.snapshot.params.id, this.datatypes[i].dataTypeId, this.datatypes[i].description, false);
this.applicationDataTypes.push(this.applicationDataType);
}
}
this.counter ++;
}
}
The line
if(undefined != this.datatypes && this.datatypes.length)
is the one giving the TypeError: Cannot read property 'length' of undefined.
This is the console error I am getting
These errors are not visible to the user and do not affect the functionality. I have tried everything, but the datatypes in the front end multi select-dropdown just keep disappearing. I have tried initializing datatypes: Datatype[] = [], wrapping my for loop with if(this.datatypes && this.datatypes.length), and using ?. These just make the multi select-dropdown empty when running the front end.
it seems like this.datatypes is not an array or its null ,you can simply ignore this error with ? .
Please Change this to if(this.datatypes?.length>0)
Can you please try as below. initialize dataTypes array, then replace for loop with forEach as below
counter: number = 0;
datatypes = [];
getDatatypes(){
if(this.counter == 0) {
if(this.appId != 0)
{
this.datatypes.forEach(dtype => {
this.applicationDataType = new ApplicationDataType(this.route.snapshot.params.id, dtype.dataTypeId, dtype.description, false);
let datatype = this.checkedDatatypes.find(y => y.description === dtype.description);
if (datatype) {
this.applicationDataType.checked = true;
this.applicationDataTypes.push(this.applicationDataType);
} else {
this.applicationDataType.checked = false;
this.applicationDataTypes.push(this.applicationDataType);
}
})
} else {
this.datatypes.forEach(dtype => {
this.applicationDataType = new ApplicationDataType(this.route.snapshot.params.id, dtype.dataTypeId, dtype.description, false);
this.applicationDataTypes.push(this.applicationDataType);
})
}
this.counter ++;
}
}

Select List values not visible - but while on debug its visible

I have a select element with values adding up to it using a javascript function which also has a value selected by default.
Everything is fine when i use the google chrome debug mode to see what has gone wrong. If i come out of the debug mode, i cant see any values, even though they are loaded.
They seem to turn back when i scroll using the select elements.
Everything seems fine in Internet Explorer and Firefox though.
Anyone faced this issue before?
Adding the code here: function call has only first 3 variables set. childSelect1 is the select element i am talking about and childOptions1 are the available options for it. The options are added based on the value in parentSelect.
function toggleChildOptions(parentSelect, childSelect1, childOptions1, childSelect2, childOptions2, addBlankEntry)
{
if(childSelect1 == null && childSelect2 == null)
{
return;
}
if(childSelect1 != null)
{
childSelect1.options.length = 0;
}
if(childSelect2 != null)
{
childSelect2.options.length = 0;
}
for (var i = 0; i < parentSelect.length; i++)
{
if(parentSelect.options[i].selected)
{
var parentID = parentSelect.options[i].value;
if(childSelect1 != null)
{
var currentChildOption1Length = childSelect1.options.length;
if (addBlankEntry == true)
childSelect1.options[currentChildOption1Length++] = new Option('',-1);
for(var j = 0; j<childOptions1.length;j++)
{
if(childOptions1[j][1] == parentID)
{
childSelect1.options[currentChildOption1Length++] = new Option(childOptions1[j][2],childOptions1[j][0]);
if (childOptions1[j][2] == '')
child1BlankFound = true;
}
}
}
if(childSelect2 != null)
{
var currentChildOption2Length = childSelect2.options.length;
if (addBlankEntry == true)
childSelect2.options[currentChildOption2Length++] = new Option('',-1);
for(var v = 0; v<childOptions2.length; v++)
{
if(childOptions2[v][1] == parentID)
{
childSelect2.options[currentChildOption2Length++] = new Option(childOptions2[v][2],childOptions2[v][0]);
}
}
}
}
}
}

At mobile device too late to use display none, block

At Pc it works well.
but mobile it is too late.
is any other faster method or the others?
function country_change(country,countries)
{
var cls = document.getElementsByClassName("country_events");
if(document.readyState == "loading")
{
alert('not loading.');
} else
{
for (n=0; n < cls.length; n++)
{
var elem = cls[n];
var div_elem = elem.getElementsByTagName('div').length;
for (m=1; m < div_elem; m++)
{
if (elem.getAttribute('name') == country)
{
if (elem.getElementsByTagName('div')[m].style.display == "none")
{
elem.getElementsByTagName('div')[m].style.display="block";
increaseHeight()
}
}
else
{
elem.getElementsByTagName('div')[m].style.display="none";
increaseHeight()
}
}
}
}
}
at pc it works about 1~3 seconds, but mobile it takes almost 10~20 sec.
i think display is not good method, but there is no other way isn't it?
The collection returned by:
var cls = document.getElementsByClassName("country_events");
is live, so any modification to the DOM may require the browser to refresh the collection. That may happen a lot more often that you think (and much more in some browsers than others), so you may want to convert that to an array or use querySelectorAll (which returns a static collection) instead:
var cls = document.querySelectorAll(".country_events");
Then you have:
var elem = cls[n];
var div_elem = elem.getElementsByTagName('div').length;
so it is good to cache elem, but getElementsByTagName also returns a live collection so use querySelectorAll again:
var div_elem = elem.querySelectorAll('div').length;
div_elem seems an inappropriate name, perhaps divCount would be better?
Then:
if (elem.getAttribute('name') == country)
you can save a method call by accessing the property directly:
if (elem.name == country)
And then the awfully wastefull:
if (elem.getElementsByTagName('div')[m].style.display == "none")
{
elem.getElementsByTagName('div')[m].style.display="block";
increaseHeight()
You got the list of divs earlier, so cache it there
var divs = elem.querySelectorAll('div');
var divCount = divs.length;
Now reuse it:
if (divs[m].style.display == 'none') {
divs[m].style.display = '';
} else {
divs[m].style.display = 'none';
}
increaseHeight();
which can be shortened to:
divs[m].style.display == divs[m].style.display == 'none'? '' : 'none';
increaseHeight();
However the conditional operator is usually slower than the equivalent if..else.
So the function becomes:
function country_change(country,countries) {
var cls = document.querySelectorAll('.country_events');
if(document.readyState == "loading") {
alert('not loading.');
} else {
for (var n=0, nLen=cls.length; n<nLen; n++) {
var elem = cls[n];
var divs = elem.querySelectorAll('div');
var divCount = divs.length;
for (var m = 1; m < divCount; m++) {
if (elem.name == country) {
if (divs[m].style.display == 'none') {
divs[m].style.display = '';
} else {
divs[m].style.display = 'none';
}
increaseHeight()
}
}
}
}
}
Note that querySelectorAll is not supported by IE 7 and lower.
Setting element.style.display to '' (empty string) allows it to return to it's default or computed style and means you don't have to know what that is for each different type of element or what is included in CSS rules.

Problem with document.forms[i][j].type, returns undefined

I'm writing a firefox addon. Here is a part of the quote
var cForm = '';
var doc = document;
for (i = 0; i < doc.forms.length; i++)
{
var a = doc.forms[i].name + "";
if ( a.search("itsMe") != -1)
{
cForm = i;
}
}
//
if ( cForm != '' )
{
for (i = 0; i < doc.forms[cForm].length; i++)
{
var sTotal = 'doc.forms[' + cForm + '][' + i +'].type';
if ( eval(sTotal) == "button")
{
return sTotal ;
}
}
}
The first code works well. The 2nd code shows an error like: "doc.forms[0][0] is undefined"
whats wrong?? help...
The issue could be in your use of eval; it might not know about doc, since it's not in scope. In general, you should try to avoid using eval. You really don't need it in this case, so try doing something like this:
if (i.length && typeof(cForm) != "undefined")
{
cForm = parseInt(cForm);
for (i = 0; i < document.forms[cForm].length; i++)
{
if (document.forms[cForm][i].type == "button")
{
return sTotal ;
}
}
}
doc.forms[0][0] could be a textarea, say, which would make it have no .type.
On a separate note, why are you using eval, exactly???

javascript - Failed to load source for: http://localhost/js/m.js

Why oh why oh why... I can't figure out why I keep getting this error. I think I might cry.
/*** common functions */
function GE(id) { return document.getElementById(id); }
function changePage(newLoc) {
nextPage = newLoc.options[newLoc.selectedIndex].value
if (nextPage != "")
{
document.location.href = nextPage
}
}
function isHorizO(){
if (navigator.userAgent.indexOf('iPod')>-1)
return (window.orientation == 90 || window.orientation==-90)? 1 : 0;
else return 1;
}
function ShowHideE(el, act){
if (GE(el)) GE(el).style.display = act;
}
function KeepTop(){
window.scrollTo(0, 1);
}
/* end of common function */
var f = window.onload;
if (typeof f == 'function'){
window.onload = function() {
f();
init();
}
}else window.onload = init;
function init(){
if (GE('frontpage')) init_FP();
else {
if (GE('image')) init_Image();
setTimeout('window.scrollTo(0, 1)', 100);
}
AddExtLink();
}
function AddExtLink(){
var z = GE('extLink');
if (z){
z = z.getElementsByTagName('a');
if (z.length>0){
z = z[0];
var e_name = z.innerHTML;
var e_link = z.href;
var newOption, oSe;
if (GE('PSel')) oSe = new Array(GE('PSel'));
else
oSe = getObjectsByClassName('PSel', 'select')
for(i=0; i<oSe.length; i++){
newOption = new Option(e_name, e_link);
oSe[i].options[oSe[i].options.length] = newOption;
}
}
}
}
/* fp */
function FP_OrientChanged() {
init_FP();
}
function init_FP() {
// GE('orientMsg').style.visibility = (!isHorizO())? 'visible' : 'hidden';
}
/* gallery */
function GAL_OrientChanged(link){
if (!isHorizO()){
ShowHideE('vertCover', 'block');
GoG(link);
}
setTimeout('window.scrollTo(0, 1)', 500);
}
function init_Portfolio() {
// if (!isHorizO())
// ShowHideE('vertCover', 'block');
}
function ShowPortfolios(){
if (isHorizO()) ShowHideE('vertCover', 'none');
}
var CurPos_G = 1
function MoveG(dir) {
MoveItem('G',CurPos_G, dir);
}
/* image */
function init_Image(){
// check for alone vertical images
PlaceAloneVertImages();
}
function Img_OrtChanged(){
//CompareOrientation(arImgOrt[CurPos_I]);
//setTimeout('window.scrollTo(0, 1)', 500);
}
var CurPos_I = 1
function MoveI(dir) {
CompareOrientation(arImgOrt[CurPos_I+dir]);
MoveItem('I',CurPos_I, dir);
}
var arImgOrt = new Array(); // orientation: 1-horizontal, 0-vertical
var aModeName = new Array('Horizontal' , 'Vertical');
var arHs = new Array();
function getDims(obj, ind){
var arT = new Array(2);
arT[0] = obj.height;
arT[1] = obj.width;
//arWs[ind-1] = arT;
arHs[ind] = arT[0];
//**** (arT[0] > arT[1]) = (vertical image=0)
arImgOrt[ind] = (arT[0] > arT[1])? 0 : 1;
// todor debug
if(DebugMode) {
//alert("["+obj.width+","+obj.height+"] mode="+((arT[0] > arT[1])? 'verical' : 'hoziontal'))
writeLog("["+obj.width+","+obj.height+"] mode="+((arT[0] > arT[1])? 'verical' : 'hoziontal')+' src='+obj.src)
}
if (arImgOrt[ind]) {
GE('mi'+ind).className = 'mImageH';
}
}
function CompareOrientation(imgOrt){
var iPhoneOrt = aModeName[isHorizO()];
GE('omode').innerHTML = iPhoneOrt;
//alert(imgOrt == isHorizO())
var sSH = (imgOrt == isHorizO())? 'none' : 'block';
ShowHideE('vertCover', sSH);
var sL = imgOrt? 'H' : 'V';
if (GE('navig')) GE('navig').className = 'navig'+ sL ;
if (GE('mainimage')) GE('mainimage').className = 'mainimage'+sL;
var sPfL = imgOrt? 'Port-<br>folios' : 'Portfolios' ;
if (GE('PortLnk')) GE('PortLnk').innerHTML = sPfL;
}
function SetGetDim( iMInd){
var dv = GE('IImg'+iMInd);
if (dv) {
var arI = dv.getElementsByTagName('img');
if (arI.length>0){
var oImg = arI[0];
oImg.id = 'Img'+iMInd;
oImg.className = 'imageStyle';
//YAHOO.util.Event.removeListener('Img'+iMInd,'load');
YAHOO.util.Event.on('Img'+iMInd, 'load', function(){GetDims(oImg,iMInd);}, true, true);
//oImg.addEventListener('load',GetDims(oImg,iMInd),true);
}
}
}
var occ = new Array();
function PlaceAloneVertImages(){
var iBLim, iELim;
iBLim = 0;
iELim = arImgOrt.length;
occ[0] = true;
//occ[iELim]=true;
for (i=1; i<iELim; i++){
if ( arImgOrt[i]){//horizontal image
occ[i]=true;
continue;
}else { // current is vertical
if (!occ[i-1]){//previous is free-alone. this happens only the first time width i=1
occ[i] = true;
continue;
}else {
if (i+1 == iELim){//this is the last image, it is alone and vertical
GE('mi'+i).className = 'mImageV_a'; //***** expand the image container
}else {
if ( arImgOrt[i+1] ){
GE('mi'+i).className = 'mImageV_a';//*****expland image container
occ[i] = true;
occ[i+1] = true;
i++;
continue;
}else { // second vertical image
occ[i] = true;
occ[i+1] = true;
if (arHs[i]>arHs[i+1]) GE('mi'+(i+1)).style.height = arHs[i]+'px';
i++;
continue;
}
}
}
}
}
//arImgOrt
}
function AdjustWebSiteTitle(){
//if (GE('wstitle')) if (GE('wstitle').offsetWidth > GE('wsholder').offsetWidth) {
if (GE('wstitle')) if (GE('wstitle').offsetWidth > 325) {
ShowHideE('dots1','block');
ShowHideE('dots2','block');
}
}
function getObjectsByClassName(className, eLTag, parent){
var oParent;
var arr = new Array();
if (parent) oParent = GE(parent); else oParent=document;
var elems = oParent.getElementsByTagName(eLTag);
for(var i = 0; i < elems.length; i++)
{
var elem = elems[i];
var cls = elem.className
if(cls == className){
arr[arr.length] = elem;
}
}
return arr;
}
////////////////////////////////
///
// todor debug
var DebugMode = (getQueryVariable("debug")=="1")
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
var sRet = ""
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
sRet = pair[1];
}
}
return sRet
//alert('Query Variable ' + variable + ' not found');
}
var oLogDiv=''
function writeLog(sMes){
if(!oLogDiv) oLogDiv=document.getElementById('oLogDiv')
if(!oLogDiv) {
oLogDiv = document.createElement("div");
oLogDiv.style.border="1px solid red"
var o = document.getElementsByTagName("body")
if(o.length>0) {
o[0].appendChild(oLogDiv)
}
}
if(oLogDiv) {
oLogDiv.innerHTML = sMes+"<br>"+oLogDiv.innerHTML
}
}
First, Firebug is your friend, get used to it. Second, if you paste each function and some supporting lines, one by one, you will eventually get to the following.
var DebugMode = (getQueryVariable("debug")=="1")
function getQueryVariable(variable)
You can't execute getQueryVariable before it is defined, you can create a handle to a future reference though, there is a difference.
There are several other potential issues in your code, but putting the var DebugMode line after the close of the getQueryVariable method should work fine.
It would help if you gave more context. For example, is
Failed to load source for:
http://localhost/js/m.js
the literal text of an error message? Where and when do you see it?
Also, does that code represent the contents of http://localhost/js/m.js? It seems that way, but it's hard to tell.
In any case, the JavaScript that you've shown has quite a few statements that are missing their semicolons. There may be other syntax errors as well. If you can't find them on your own, you might find tools such as jslint to be helpful.
make sure the type attribute in tag is "text/javascript" not "script/javascript".
I know it is more than a year since this question was asked, but I faced this today. I had a
<script type="text/javascript" src="/test/test-script.js"/>
and I was getting the 'Failed to load source for: http://localhost/test/test-script.js' error in Firebug. Even chrome was no loading this script. Then I modified the above line as
<script type="text/javascript" src="/test/test-script.js"></script>
and it started working both in Firefox and chrome. Documenting this here hoping that this will help someone. Btw, I dont know why the later works where as the previous one didn't.

Categories

Resources