Java Script Function is not Defined JSP Error - javascript

I keep getting "function is not defined" errors while working on a Javascript/HTML page.
EDIT: Updated Link: http://jsfiddle.net/Gmyag/134/
EDIT: Updated link http://puu.sh/8CxnC/b954c1c803.html is the actual one I'm working with and would likely prove leagues more useful than the fiddle.
HTML:
deliveryIdentification is the one giving issues. Code too long.
Had to add code block since I added a jsfiddle.
Sorry for not simplifying the example, but this is the first time I've seen this.
If I put everything on a separate script blocks others seem to work, but with the addDelRefOrder() since I need to declare var deliveryDummy[] before it throws "ReferenceError: deliveryDummy is not defined. And if I put deliveryDummy[] in the same block it says "ReferenceError:addDelRefOrder() is not defined".
As to why the structure is so weird it's due to it being a .jsp file. I'm just starting out with JSP and learning a lot along the way.
Any and all help as of how to fix this issue is greatly appreciated.

You are defining function inside function ? Here
function renderList()
{
// clean the list:
while (list.firstChild) {
list.removeChild(list.firstChild);
}
// Recreate li
for(var i = 0; i < deliveryDummy.length; i++) {
var entry = document.createElement("li");
entry.appendChild(document.createTextNode(deliveryDummy[i]));
var removeButton = document.createElement('button');
removeButton.appendChild(document.createTextNode("Remove"));
removeButton.setAttribute('onClick','removeName('+i+')');
entry.appendChild(removeButton);
list.appendChild(entry);
}
function removeDeliver(deliverIndex){
deliverDummy.splice(deliverIndex,1);
// Array changed to re-render List
renderList();
}
function getDeliver() {
return deliverDummy;
}
}
you have renderList() and inside this two more funcs. This is the wrong structure for Javascript. Make separate functions.

I'm not very familiar with jsp either but your HTML tagging is a little messy.
Make sure that the html tags are properly nested.

in your javascript i noticed that you have made calls to functions before you have created them. first fix this issue and see if it resolves your problem.
window.onload=function addDelRefOrder()
{
var deliveryVal = document.getElementById("deliveryIdentification").value;
// Add to array
deliveryDummy.push(deliveryVal);
// Array changed, Re-Render
renderList(); /// <==== HERE
}
window.onload=function renderList() // <====== Function created here.
{
// clean the list:
while (list.firstChild) {
list.removeChild(list.firstChild);
}
// Recreate li
for(var i = 0; i < deliveryDummy.length; i++) {
var entry = document.createElement("li");
entry.appendChild(document.createTextNode(deliveryDummy[i]));
var removeButton = document.createElement('button');
removeButton.appendChild(document.createTextNode("Remove"));
removeButton.setAttribute('onClick','removeName('+i+')');
entry.appendChild(removeButton);
list.appendChild(entry);
}
}

Related

Ember control does not come back to loop after sending action

In my Ember app, I have the following code to remove checked rows dynamically
removeRow: function(row){
// Some logic to remove one row at a time
var numberContainers = this.get('containers').length;
for (var i = 0; i < numberContainers; i++){
}
}
this.get('containers').forEach(function(container){
if (container.applicable === true){
var row = {};
self.send("removeRow", row);
}
})
Now user can select multiple rows & try removing them. With the above code, the "removeRow" action is invoked only once i.e. the forEach loop somehow gets broken or control does not come back again after the "removeRow" action is invoked once.
How can I handle this scenario ?
A couple of things were mentioned in comments. You have some different smells and errors:
While you're iterating on an array, you are trying to modify it.
Instead of calling a function of the component, you are sending an action to call it.
It is not clear var row = {}; self.send("removeRow", row); If a container is suitable why we are removing a newly created row object?
Anyway, my suggestions are:
Separate the array modification and iteration
Define removeRow as a function, if you need to use it as an action handler also define an action handler and delegate the whole responsibilty to the function.
Here is a sample code:
removeRow: function(row){
// Some logic to remove one row at a time
var numberContainers = this.get('containers').length;
for (var i = 0; i < numberContainers; i++){
}
}
otherFunction(){
let applicables = this.get('containers').filterBy('applicable', true);
applicables.forEach(a=>{let row={};this.removeRow(row);});
}
actions:{
removeRow(row){
this.removeRow(row);
}
}

Pass a Parameter to Another Function and Into innerHTML

I've built my own lightbox, and it's working rather well. I built my own because I needed it to be without a framework, and also work well within a game I'm building. However, I've run into a problem I'm fairly certain is simple, but proving rather vexing to me. The issue I'm having is taking the parameter "slideName" and passing it through to the "fillRightButton()" function.
var createSlidebox = function(cancelButton, bannerImg, slideName) {
fillRightButton("nextSlide",slideName);
};
Here's a portion of that function:
var fillRightButton = function(rightButtonType, rightDestination) {
if (rightButtonType === "nextSlide") {
document.getElementById("lightbox_fright").innerHTML = '<a onclick="changeSlide(' + rightDestination + ')">Next</a>';
}
}
The "fillRightButton()" function performs fine when it is called directly, and this code works if you put the parameter in directly:
var createSlidebox = function(cancelButton, bannerImg, slideName) {
fillRightButton("nextSlide", "mySlideName");
};
However, without the quotes it renders as:
<a onclick="changeSlide([object Object])">Next</a>
with a "Uncaught SyntaxError: Unexpected identifier" JS error. How would I fix this? Thanks!
use data attribute to store the object using jQuery, in function call
var fillRightButton = function(rightButtonType, rightDestination) {
if (rightButtonType === "nextSlide") {
document.getElementById("lightbox_fright").innerHTML = '';
// document.getElementById("lightbox_fright").innerHTML = '<a onclick="changeSlide( $(this).data('dest') )">Next</a>';
var a = document.createElement('a');
a['data-dest'] = rightDestination;
a.onclick=function(){changeSlide( this['data-dest']); }
a.innerHTML = 'Next';
document.getElementById("lightbox_fright").appendChild(a);
//document.getElementById('lightbox_fright > a').data({'dest':rightDestination});
}
}
use jQuery if not already included
PS updated w/o jQuery please give it a try let me know if it works, recommend using jQuery though

How to add array to parameter with function?

I am very new to programming and I am wondering if anyone can help me with this.
I am trying to make a pop up page.
I set variables for each click area which I set each area with div and placed with css.
Also for each pop up image which I put div id on each image on html and set display = "none" on css.
I want to make a function that shows one image on touchend and hide other images at the same time.
Could you help me with my code?
var pop = new Array("pop1","pop2","pop3","pop4","pop5","pop6");
var clickArea = new Array("click1","click2","click3","click4","click5","click6");
function diplay(click,show,hide){
click.addEventListner("touchend",function(){
show.style.display = "block";
hide.style.display = "none";
});
};
display("click[0]","pop[0]","pop[1,2,3,4,5]");
There are a few different issues with your code.
You used strings instead of the actual code structure references while calling display. I see that you mean for these to reference the element ids, but you must first get the element with document.getElementById(...) or jQuery's $("#...").
In the pop and clickArea arrays, you used strings, which do not have the .style object. You need to reference the elements themselves.
Your code structure is not designed to handle arrays.
You need to define the addEventListener before you need the function handler to be called. You do not want this every time.
The click argument in the display function is redundant, as it is never called.
You are using jQuery. You should have stated this! (but you're forgiven) :)
You can't reach into arrays with the syntax arrayName[#,#,#].
You misspelled "display". Whoops!
The arrays are redundant, since the code needed to be restructured.
First, in order to address Point #4, we need this code to run when the DOM has finished loading:
var clickArea = new Array("click1","click2","click3","click4","click5","click6");
clickArea.each(function(id){
$("#"+id)[0].addEventListener("touchend", display);
});
Next, we need to fix the issues with your code. They're explained above.
var pop = new Array("pop1","pop2","pop3","pop4","pop5","pop6");
function display(event){
var indx = Number(event.target.id.split(/\D/i).join(""));
$("#pop"+indx)[0].style.display = "block";
pop.each(function(ide) {
if (ide.split(/\D/i).join("") != indx-1) {
$("#"+ide)[0].style.display = "none";
}
});
};
Otherwise, great job! All of us started out like this, and believe in you! Keep it up!
P.S. You can set arrays like this [ ? , ? , ? , ? ] instead of this new Array( ? , ? , ? , ? ).
Here is an example using for loops instead of methods of Arrays etc
Start off by defining everything you can
var popup_id = ["pop1", "pop2", "pop3", "pop4", "pop5", "pop6"],
popup_elm = [], // for referencing the elements later
area_id = ["click1", "click2", "click3", "click4", "click5", "click6"],
area_elm = [], // for referencing the elements later
i; // for the for -- don't forget to var everything you use
// a function to hide all popups
function hideAll() {
var i; // it's own var means it doesn't change anything outside the function
for (i = 0; i < popup_elm.length; ++i) {
popup_elm.style.display = 'none';
}
}
// a function to attach listeners
function listenTouch(area, popup) {
area.addEventListener('touchend', function () {
hideAll();
popup.style.display = 'block';
});
// we did this in it's own function to give us a "closure"
}
Finally we are ready do begin linking it all to the DOM, I'm assuming the following code is executed after the elements exist in the browser
// setup - get Elements from ids, attach listeners
for (i = 0; i < popup_id.length; ++i) {
popup_elm[i] = document.getElementById(popup_id[i]);
area_elm[i] = document.getElementById(area_id[i]);
listenTouch(area_elm[i], popup_elm[i]);
}
You cannot treat strings as html elements.
Assuming there are elements with click area ids in the page, you may do something like (once the document is ready).
var popEls = pop.map(function (id) { return document.getElementById(id) });
clickArea.forEach(function (id) {
var clickAreaEl = document.getElementById(id);
clickAreaEl.addEventListener('click', onClickAreaClick);
});
function onClickAreaClick() {
var clickAreaNum = +this.id.match(/\d+$/)[0],
popIndex = clickAreaNum - 1;
popEls.forEach(function (popEl) {
popEl.style.display = 'none';
});
popEls[popIndex].style.display = 'block';
}

Trouble with my javascript function, I think with document.getElementById('vodObj').innerHTML

I am trying to write a JavaScript function that will update the labels and attributes of my CSS menu. The CSS menu I create dynamically with PHP and a database, and I want to update the CSS menu so the top item is the currently selected one, and the currently selected one does not appear in the list below it. Now that you know what I am trying to accomplish, here is my code:
var vodName = Array();
var vodAddress = Array();
var vodDate = Array();
function switchVod(vodID) {
alert("switchVod ran");
var x = document.getElementById("vod1");
var y = x.getElementsByTagName("span");
y[0].innerHTML = vodName[vodID];
for (var i = 0; i < vodName.length; i++) {
if (i != vodID) {
var gameNum = i + 2;
var gameID = "vod" + gameNum;
var x = document.getElementByID(gameID);
var y = x.getElementsByTagName("span");
y[0].innerHTML = vodName[i]
x.onclick = function () {
switchVod(id);
}
}
}
alert("after for loop");
alert("1"); //works
document.getElementById('vodObj').innerHTML = 'some string';
alert("2"); //doesn't work
document.getElementById("vodDate").innerHTML = " some string ";
alert("finished"); //doesn't work
}
Deeper in the webpage, after getting my information from the database and storing the strings I need in the vodName, vodAddress, and vodDate arrays, and creating the CSS menu and <div id="vodObj"> and <div id="vodDate">, I initialize the page by calling
window.onload = switchVod(0);
It wasn't doing what I hoped, so I added some alert() calls to see how far into the function it was going before failing. alert("after for loop") worked, as did alert("1"). But, alert("2") does not pop up, and neither does alert("finished"), so I think the problem is with document.getElementById('vodObj').innerHTML = 'some string';.
Any ideas of what I could be doing wrong?
window.onload = switchVod(0);
executes switchVod and assigns the return value to window.onload. So it is very likely that the elements you are trying to access (#vodObj in particular) are not loaded yet.
You have to assign a function to window.onload:
window.onload = function() {
switchVod(0);
};
See also Why does jQuery or a DOM method such as getElementById not find the element?
There is an other problem which will encounter eventually:
x.onclick = function () {
switchVod(id);
}
You never defined id anywhere, and if you define it inside the loop, you will run into closure issues. See JavaScript closure inside loops – simple practical example for a solution.
y[0].innerHTML = vodName[vodID];
At this point vodName is an empty array. Actually throughout all of this, you never provide any values to vodName. Please provide complete document.

Jquery click bindings are not working correctly when binding multiple copies

I seem to have an issue when creating copies of a template and tying the .click() method to them properly. Take the following javascript for example:
function TestMethod() {
var test = Array();
test[0] = 0;
test[1] = 1;
test[2] = 2;
// Insert link into the page
$("#test_div").html("<br>");
var list;
for (x = 0; x < test.length; x++) {
var temp = $("#test_div").clone();
temp.find('a').html("Item #" + test[x]);
temp.click(function () { alert(x); });
if (list == undefined)
list = temp;
else
list = list.append(temp.contents());
}
$("#test_div2").append(list);
}
The problem I am seeing with this is that no matter which item the user clicks on, it always runs alert(2), even when you click on the first few items.
How can I get this to work?
Edit: I have made a very simple example that should show the problem much clearer. No matter what item you click on, it always shows an alert box with the number 2 on it.
Correct me if I'm wrong, .valueOf() in JS returns the primitive value of a Boolean object.....
this would not happen ShowObject(5,'T');... ShowObject(objectVal.valueOf(), 'T');
why not use objects[x].Value directly? ShowObject(objects[x].Value, 'T');
WOOOOOSSSHHHH!
after searching deeply... I found a solution...
because it's a closure, it won't really work that way...
here's a solution,
temp.find('a').bind('click', {testVal: x},function (e) {
alert(e.data.testVal);
return false;
});
for best explanation, please read this... in the middle part of the page where it says Passing Event Data a quick demo of above code
I think your issue arises from a misunderstanding of scopes in JavaScript. (My apologies if I'm wrong.)
function () {
for (...) {
var foo = ...;
$('<div>').click(function () { alert(foo); }).appendTo(...);
}
}
In JavaScript, only functions create a new scope (commonly referred to as a closure).
So, every round of the for loop will know the same foo, since its scope is the function, not the for. This also applies to the events being defined. By the end of looping, every click will know the same foo and know it to be the last value it was assigned.
To get around this, either create an inner closure with an immediately-executing, anonymous function:
function () {
for (...) {
(function (foo) {
$('<div>').click(function () { alert(foo); }).appendTo(...);
})(...);
}
}
Or, using a callback-based function, such as jQuery.each:
function () {
$.each(..., function (i, foo) {
$('<div>').click(function () { alert(foo); }).appendTo(...);
});
}
For your issue, I'd go with the latter (note the changes of objects[x] to just object):
var list;
jQuery.each(data.objects, function (x, object) {
// Clone the object list item template
var item = $("#object_item_list_template").clone();
// Setup the click action and inner text for the link tag in the template
var objectVal = object.Value;
item.find('a').click(function () { ShowObject(objectVal.valueOf(), 'T'); }).html(object.Text);
// add the html to the list
if (list == undefined)
list = item;
else
list.append(item.contents());
});

Categories