javascript function return "undefine" from jsp page - javascript

i have a jsp page and call a JS function which is in some abc.js file from this JSP page.
i have included this js file to jsp page.
JSP JavaScript Code:-
function doFinish(tableId, col, field)
{
var oldselectedCells = "";
var selItemHandle = "";
var selRightItemHandle = "";
var left = -1;
var right = -1;
// Get the table (tBody) section
var tBody = document.getElementById(tableId);
// get field in which selected columns are stored
var selectedCellsFld = document.getElementById(tableId + datatableSelectedCells);
selectedCellsFld.value = oldselectedCells;
for (var r = 0; r < tBody.rows.length; r++)
{
var row = tBody.rows[r];
if (row.cells[col].childNodes[0].checked == true)
{
selectedCellsFld.value = oldselectedCells +
row.cells[col].childNodes[0].id;
selItemHandle = row.cells[col].childNodes[0].value
oldselectedCells = selectedCellsFld.value + datatableOnLoadDivider;
left = selItemHandle.indexOf("=");
right = selItemHandle.length;
selRightItemHandle = selItemHandle.substring(left+1,right);
var index=getColumnIndex(tBody,"Name");
if(index!=null)
{
if(field == 1)
{
window.opener.document.TemplateForm.eds_asbactionscfg_item_handle_child_physpart.value = selRightItemHandle;
window.opener.document.TemplateForm.ChildPhysicalPart.value = row.cells[index].childNodes[0].innerHTML;
}
else if (field == 2)
{
window.opener.document.TemplateForm.eds_asbactionscfg_dev_doc_item_handle_name.value = selRightItemHandle;
window.opener.document.TemplateForm.DeviationObject.value = row.cells[index].childNodes[0].innerHTML;
}
else if (field == 3)
{
window.opener.document.TemplateForm.eds_asbactionscfg_dev_doc_item_handle_name.value = selRightItemHandle;
window.opener.document.TemplateForm.DeviationObject.value = row.cells[index].childNodes[0].innerHTML;
}
}
}
}
window.close();
}
JS Code:-
function getColumnIndex(tBody,columnName)
{
var cells = tBody.parentNode.getElementsByTagName('th');
for (var i=0;i<cells.length; i++)
{
if(cells[i].hasChildNodes())
{
if(cells[i].childNodes[0].innerHTML.replace(/(\r\n|\n|\r)/gm ,"").trim() == columnName)
{
return i;
}
}
}
}
i had debug this code with firebug & calling getColumnIndex(tBody,columnName) function works fine but when it return to caller the var index=getColumnIndex(tBody,"Name"); the index value is "undefine".
suggest some solution.

getColumnIndex(tBody,columnName) function works fine.
as if it matches this if condition
if(cells[i].childNodes[0].innerHTML.replace(/(\r\n|\n|\r)/gm ,"").trim() == columnName)
{
return i;
}
so that it returns something.
but when you replace this
var index=getColumnIndex(tBody,"Name"); so that coulmnName would be "Name" in String.
And it doesn't match with any columnName so that your condition going to be wrong and function doesn't return anything.
var index=getColumnIndex(tBody,"Name"); the index value is "undefine".
suggestion is put some else condition on that and return some error message like this :
if(cells[i].childNodes[0].innerHTML.replace(/(\r\n|\n|\r)/gm ,"").trim() == columnName)
{
return i;
} else{
// put some error message
// return null
}

i had debug this code with firebug & calling getColumnIndex(tBody,columnName) function works fine
From this, I'm assuming that there isn't anything wrong with the implementation of your getColumnIndex function, so your issue with getting an undefined value must have to do with when this function is returning a value.
but when it return to caller the var index=getColumnIndex(tBody,"Name"); the index value is "undefine".
This leads me to assume that your tBody variable is not being set correctly, given that the "function works fine".
I'm assuming there is a case in your code where the conditions of your getColumnIndex function is not met.
function getColumnIndex(tBody,columnName)
{
var cells = tBody.parentNode.getElementsByTagName('th');
for (var i=0;i<cells.length; i++)
{
if(cells[i].hasChildNodes())
{
if(cells[i].childNodes[0].innerHTML.replace(/(\r\n|\n|\r)/gm ,"").trim() == columnName)
{
return i;
}
}
}
// If your code reaches this point, then the prior conditions have not been met
// You can choose to do something else here for return false/undefined etc.
return undefined;
}

Related

I am trying to get some data from user input into a JSON file.I get this message

I get this JSON error that tells me that I have a syntax error an I can't figure out where I made the mistake. I have provided the code in case if helps.
var isNode= typeof module !=="undefined"
var clientData;
var auxClientData;
var aux=[];
var k=0;
if (!isNode)
{
var storedObjects=JSON.parse(localStorage.getItem("objects"));
console.log(storedObjects);
var ok=false;
buttonConfirm.addEventListener("click",function(){
for(var i=0;i<inputs.length;i++)
{
var inputShow=inputs[i].value;
if (inputShow!=null && inputShow!="")
{
aux[k++]=inputShow;
}
else
{
alert("ALL THE FIELDS MUST BE COMPLETED! ");
ok=true;
break;
}
}
clientData={fullName:aux[0],emailAddress:aux[1],phoneNumber:aux[2]};
//localStorage.setItem("clientData",JSON.stringify(clientData));
// console.log(clientData);
if (ok==true){
alert("THANK YOU FOR YOUR PURCHASE! CHECK YOUR E-MAIL")
}
console.log(JSON.parse(JSON.stringify(clientData)));
})
}
else
{
var clientData={"fullName":aux[0],"emailAddress":aux[1],"phoneNumber":aux[2]};
var fs=require("fs");
auxClientData=JSON.stringify(clientData);
fs.writeFile("clients.json",auxClientData,finished)
function finished()
{
console.log("ok");
var ok=fs.readFileSync("clients.json");
var test=JSON.parse(ok);
console.log(test);
}
}
Here is the error:
SyntaxError: Unexpected end of JSON input
at JSON.parse ()
I've just realised what the problem is :
var clientData;
auxClientData=JSON.stringify(clientData);
clientData inside your else statement is never set and it will be undefined. so you will need to redefine it inside the else. aux will need to be available and in scope further up your program for this to work. You can confirm my assumption by manually setting clientData to something else inside the else statement.
else
{
var fs=require("fs");
clientData={"fullName":aux[0],"emailAddress":aux[1],"phoneNumber":aux[2]};
auxClientData=JSON.stringify(clientData);
fs.writeFile("clients.json",auxClientData,finished)
function finished()
{
console.log("ok");
}
var ok=fs.readFileSync("clients.json");
var test=JSON.parse(ok);
console.log(test);
}
------------------------------YOUR CODE.
var isNode = typeof module !== "undefined"
var clientData;
var auxClientData;
var aux = [];
var k = 0;
if (!isNode) {
// INSIDE THE IF
var storedObjects = JSON.parse(localStorage.getItem("objects"));
console.log(storedObjects);
var ok = false;
//add a listener inside the if statement for the click.
buttonConfirm.addEventListener("click", function () {
// when it is clicked.
for (var i = 0; i < inputs.length; i++) {
var inputShow = inputs[i].value;
if (inputShow != null && inputShow != "") {
//POPULATE THE AUX ARRAY adding one to k each time?
// seems weird, why is this not aux[i] = inputShow;
aux[k++] = inputShow;
}
else {
alert("ALL THE FIELDS MUST BE COMPLETED! ");
ok = true;
break;
}
}
clientData = { fullName: aux[0], emailAddress: aux[1], phoneNumber: aux[2] };
//localStorage.setItem("clientData",JSON.stringify(clientData));
// console.log(clientData);
if (ok == true) {
alert("THANK YOU FOR YOUR PURCHASE! CHECK YOUR E-MAIL")
}
console.log(JSON.parse(JSON.stringify(clientData)));
})
}
else {
//inside the else.
//aux is an empty array here. so aux[0] = undefined, aux[1] = undefined etc.
//i.e. the button hasn't been pressed to populate it at this point.
var clientData = { "fullName": aux[0], "emailAddress": aux[1], "phoneNumber": aux[2] };
var fs = require("fs");
auxClientData = JSON.stringify(clientData);
fs.writeFile("clients.json", auxClientData, finished)
function finished() {
console.log("ok");
var ok = fs.readFileSync("clients.json");
var test = JSON.parse(ok);
console.log(test);
}
}

JavaScript Check multiple variables being empty

I'm trying the following code:
var var1 = "";
var var2 = "test";
var var3 = "";
vars = new Array('var1','var2','var3');
var count = 0;
for (var i = 0; i < vars.length; ++i) {
var name = vars[i];
if (field_is_empty(name)) {
count++;
}
}
console.log(count);
function field_is_empty(sValue) {
if (sValue == "" || sValue == null || sValue == "undefined")
{
return true;
}
return false;
}
The result here should have been count = 2 because two of the variables are empty but it's always 0. I guess it must something when using if (field_is_empty(name)) because it might not getting the name converted to the name of the actual var.
PROBLEM 2# Still related
I've updated the code as Karthik Ganesan mentioned and it works perfectly.
Now the code is:
var var1 = "";
var var2 = "test";
var var3 = "";
vars = new Array(var1,var2,var3);
var count = 0;
for (var i = 0; i < vars.length; ++i) {
var name = vars[i];
if (field_is_empty(name)) {
count++;
}
}
console.log(count);
function field_is_empty(sValue) {
if (sValue == "" || sValue == null || sValue == "undefined")
{
return true;
}
return false;
}
And the problem is that if add a new if statement something like this:
if (count == '3') {
console.log('AllAreEmpty');
} else {
for (var i = 0; i < vars.length; ++i) {
var name = vars[i];
if (field_is_empty(name)) {
//Set the empty variables as "1900-01-01"
variableService.setValue(name,"test");
}
}
}
It does nothing and I've tested using variableService.setValue('var1',"test") and it works.
PS: The variableService.setValue is a function controlled by the software I don't know exactly what it does I know if use it like mentioned on above line it works.
In your first attempt you used the variable names as strings when you created an array. You need to either use the values themselves:
vars = new Array(var1,var2,var3);
or if you insist to use them by their names, then you need to find them by names when you use them:
if (field_is_empty(window[name])) {
It does nothing
That's not really possible. It could throw an error, or enter the if or enter the else, but doing nothing is impossible. However, since you intended to use the variables by name in the first place (probably not without a reason) and then you intend to pass a name, but it is a value and it does not work as expected, I assume that your initial array initialization was correct and the if should be fixed like this:
var var1 = "";
var var2 = "test";
var var3 = "";
vars = new Array(var1,var2,var3);
var count = 0;
for (var i = 0; i < vars.length; ++i) {
var v = window[vars[i]]; //You need the value here
if (field_is_empty(v)) {
count++;
}
}
console.log(count);
if (count == '3') {
console.log('AllAreEmpty');
} else {
for (var i = 0; i < vars.length; ++i) {
var v = window[vars[i]];
if (field_is_empty(v)) {
//Set the empty variables as "1900-01-01"
variableService.setValue(vars[i],"test");
}
}
}
function field_is_empty(sValue) {
if (sValue == "" || sValue == null || sValue == "undefined")
{
return true;
}
return false;
}
You definitely incorrectly initialize array, you put strings "var1", "var2", "var3" instead of references to strings (variables).
Try this:
vars = new Array(var1,var2,var3);
Your array is wrong
it should be
vars = new Array(var1,var2,var3);
here is the jsfiddle

Breaking from a recursive function and returning a value in Javascript

I have written a javascript function like this . But I want when a cretain condition meet the function will not execute means it will break and return a true false like status.My code is like this
var ActionAttributes = function (data)
{
var status = true;
var attrKey = data.AttributeKey();
//Condition to exit
if (attrKey==''||attrKey==null)
{
status = false;
return false;
}
for (var i = 0; i < data.Children().length; i++)
{
var childData = data.Children()[i];
ActionAttributes(childData);
}
return status;
}
You need break condition in the for loop. You are just invoking it, handle the returned status.
var ActionAttributes = function(data) {
var status = true;
var attrKey = data.AttributeKey();
//Condition to exit
if (attrKey == '' || attrKey == null) {
status = false;
return false;
}
for (var i = 0; i < data.Children().length; i++) {
var childData = data.Children()[i];
//You need to break loop here
//Add appropriate condition here
if (ActionAttributes(childData) == false) {
return false;
}
}
return status;
}
well, that recursion is not very useful to begin with.
you call a recursion of ActionAttributes inside the loop, but never handle the returned status. So the first caller will always receive true unless the exit condition meets on the first object.
you shoul store the return from ActionAttributes into status, and then break out of the loop as soon as it's false.

Javascript Recursion returning undefined

I'm struggling in a recursive Javascript function to find a specific subdirectory. This is my code:
function navigateToParent() {
var parentFullPath = parentDirectory(); // gets the full Path String
if (parentFullPath != null) {
var parent = getDirectoryByName(parentFullPath, rootDirectory);
// set the parent directory object as the current one
currentDirectory(parent);
}
}
function getDirectoryByName(fullName, myDirectory) {
if (myDirectory.fullName == fullName) {
return myDirectory;
} else {
var subs = myDirectory.subDirectories;
for (i = 0; i < subs.length; i++) {
return getDirectoryByName(fullName,subs[i]);
}
}
}
Every directory object has the properties fullName(string),subDirectories(array of directories) and files(array of files). My aim is to get the correct directory object, where it's fullName is matching.
I know, that i have to break the for loop in some way, but i don't know how to do it exactly.
After overthinking the logic i came to this solution (seems to work):
function getDirectoryByName(fullName, myDirectory) {
if (myDirectory.fullName == fullName) {
return myDirectory;
} else {
var subs = myDirectory.subDirectories;
for (i = 0; i < subs.length; i++) {
var match = getDirectoryByName(fullName, subs[i]);
if (typeof match !== "undefined"){
return match;
}
}
}
}

Javascript undefined error on last iteration

When looping through this string, the alert prints out test 4 times (correctly) but then also prints "undefined" at the end. How do I make it doesn't return undefined.
This returns - undefinedCAFE ::
alert(match("abcdef", "CAfe"));
function match(string, pattern) {
var patternUpperCase = pattern.toUpperCase();
var stringUpperCase = string.toUpperCase();
var stringConcatenate;
var answer;
for (var i = 0; i < patternUpperCase.length; i++) {
if (patternUpperCase.charAt(i) != undefined) {
if (patternUpperCase.charAt(i) >= 'A' && patternUpperCase.charAt(i) <= 'Z') {
stringConcatenate += patternUpperCase.charAt(i);
alert("test");
}
}
}
return stringConcatenate;
}
The match function doesn't have a return statement, so it returns undefined. This means that
alert(match("abcdef","CAfe"));
will always show an alert of "undefined" at least once. To not show the alert, call the function without using alert:
match("abcdef","CAfe");
Alternatively you can make the function return something, such as stringConcatenate, which would be computed for no reason otherwise.
try this
alert(match("abcdef", "CAfe"));
function match(string, pattern) {
var patternUpperCase = pattern.toUpperCase();
var stringUpperCase = string.toUpperCase();
var stringConcatenate;
var answer;
var i = 0;
for (var i = 0; i < patternUpperCase.length; i++) {
if (patternUpperCase.charAt(i) != undefined) {
if (patternUpperCase.charAt(i) >= 'A' && patternUpperCase.charAt(i) <= 'Z') {
stringConcatenate = stringConcatenate + patternUpperCase.charAt(i);
alert("test");
}
}
}
return stringConcatenate;
}
Last "undefined" valie is result of your function:
alert(match("abcdef", "CAfe"));
http://jsfiddle.net/sava/Dw7jm/

Categories

Resources