variable as element of method call in a loop - javascript

I am trying to get the content from CKEDITOR for every div with the id change (change1, change2, ...)
var data2= CKEDITOR.instances.change1.getData();
for (var i = 2; i <= 30; i++){
if (typeof([\"CKEDITOR.instances.change\"+i]) != 'undefined') {
var edit = CKEDITOR.instances.change[i].getData();
data2 = data2 + '</div><div class=\"d W1 h1\">' + edit;
}}
I've tried it like this but getting error:TypeError: CKEDITOR.instances.change is undefined at
var edit = CKEDITOR.instances.change[i].getData();

Do not use typeof('...') because it will always return the typeof that object which is an object in you case, and then != from undefined...
try this:
if (CKEDITOR.instances['change' + i]) {
// put your code here
}

Related

How to update Firebase multiple times

so when trying to go through a loop that checks, updates, and posts data to my Firebase storage, it seems that whenever I try to use the Firebase.update(), then it messes with my for loop and it repeats incrementations or doesn't increment at all. Any advice?
My Code:
var j = 0;
var k = 0;
var l = 0;
var m = 0;
var setDict = {};
for(var h = 0; h < teamWinNames.length; h++)
{
console.log(j);
console.log(h);
console.log(meWinList[j]);
var tempRef = new Firebase("https://mycounter-app.firebaseio.com/user/" + username + "/championData");
var tempName = teamWinNames[h];
tempRef.once("value", function (teamWinSnapshot)
{
var exists = teamWinSnapshot.child(meWinList[j] + '/' + tempName).exists();
console.log(exists);
if(exists == true)
{
console.log("Here");
var tempVal = teamWinSnapshot.child(meWinList[j] + '/' + tempName).val();
console.log(tempVal);
//var tempValue = obj[tempname][tempchamp];
//console.log(tempValue);
}
else
{
setDict[tempName] = '1-0-0-0';
console.log(setDict);
}
});
if(h != 0 && (h+1)%4 == 0)
{
sendUpdate(setDict, meWinList[j], username);
setDict = {};
j++;
}
}
and the function that makes the update:
function sendUpdate(data, champ, username)
{
var tempRef = new Firebase("https://mycounter-app.firebaseio.com/user/" + username + "/championData");
tempRef.child(champ).update(data);
}
The problem is that you are getting your data in the for loop and also changing it inside the loop. This means that the data you are using in your loop changes with each iteration. And as an added bonus you get the effects of the asynchronous nature of firebase that can look something like this:
Get data (1)
Get data (2)
Update data (1)
Get data (3)
Update data (3)
Update data (2)
To prevent all this i suggest putting the for loop inside the tempRef.once function like this: (pseudo code)
tempRef.once{
Loop through data{
Change data
}
Update data
}
This means you only have to get the data once and update it once.

Unable to get property 'parentNode' of undefined or null reference

My javascript program basically creates a series of images and randomly picks one and sets its src to a particular path. However, for some reason, the code seems to get stuck sometimes. In my program, I'm calling element.parentNode of one of the images in order to surround it with an anchor tag but it throws a console error saying that it is unable to get property 'parentNode' of undefined or null reference despite the fact that sometimes, the code actually executes sometimes without any changes to the code. I have to refresh multiple times before I get lucky enough to have the error not be thrown and the rest of the code executed smoothly.
Here is my code:
var id = generateRandom(325);
var el = document.getElementById(id.toString());
var anchor = document.createElement("a");
var nextPage = "level" + (level + 1).toString() + ".html";
if (level == 3) {
nextPage = "win.html";
}
anchor.setAttribute("href", nextPage);
el.parentNode.insertBefore(anchor, el); // line 54
The error:
SCRIPT5007: Unable to get property 'parentNode' of undefined or null reference
scripts.js (54,2)
EDIT:
updated entire function
var div = document.getElementById("images");
var time = parseInt(document.getElementsByClassName("timer")[0].innerHTML);
var level = getLevel(time);
var rows = 13;
var cols = 23;
for (var i = 1; i <= rows; i++) {
var marquee = document.createElement("marquee");
marquee.setAttribute("scrollamount", 30);
for (var j = 1; j <= cols; j++) {
var img = document.createElement("img");
img.setAttribute("src", getPath());
img.setAttribute("id", (i * j).toString());
img.setAttribute("width", "80px");
img.setAttribute("height", "70px");
marquee.appendChild(img);
}
div.appendChild(marquee);
}
var id = generateRandom(rows * cols);
var el = document.getElementById(id.toString());
var anchor = document.createElement("a");
var nextPage = "level" + (level + 1).toString() + ".html";
if (level == 3) {
nextPage = "win.html";
}
anchor.setAttribute("href", nextPage);
el.parentNode.insertBefore(anchor, el);
var input = document.createElement("input");
input.setAttribute("type", "image");
input.setAttribute("width", "80px");
input.setAttribute("height", "70px");
input.setAttribute("src", "resources\\asotigue.jpg");
el.parentNode.replaceChild(input, el);
anchor.appendChild(input);
generateRandom function:
function generateRandom(n) {
return Math.floor((Math.random() * n) + 1);
}
This method will collect all the ids on items with a certain class available on the page right now, and will return one of the ids randomly.
You can see it at work in this fiddle. Check the console.
function getIdsListByClassName(className) {
var elements = document.querySelectorAll('[id].' + className); // get all items that have the id attribute and the defined class name
var ids = Array.prototype.slice.call(elements, 0).map(function (element) {
return element.getAttribute('id');
}); // convert the elements list to array, and map it to ids
var currentIndex = Math.floor(Math.random() * ids.length); // get an index between 0 and ids.length - 1
return ids[currentIndex];
}
Edit now that you've included more code: You are generating 13 * 23 = 299 elements, yet selecting a random element up to 325 so sometimes you don't have enough elements for your random selection.
So, what this code is telling you is that the el variable is undefined or null. There are a couple reasons why that could be:
Your generateRandom(325) is generating an id value that is not present in the page.
You are calling document.getElementById(id.toString()); before the page has finished loading and parsing and thus some page elements are not yet present. Your script should not be run until after the page has been loaded either by moving it to the end of the <body> or by waiting until the DOMContentLoaded event fires.
FYI, if your issue is the second, you can read about various solutions using plain Javascript here pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it.
If you know that sometimes generateRandom(325) will pick an element id that is not in the page and you want to allow that, but defend against it stopping execution of your code, then you can just check for that condition:
var id = generateRandom(325);
var el = document.getElementById(id.toString());
var anchor = document.createElement("a");
var nextPage = "level" + (level + 1).toString() + ".html";
if (level == 3) {
nextPage = "win.html";
}
anchor.setAttribute("href", nextPage);
if (el) {
el.parentNode.insertBefore(anchor, el);
}
To help you track down your occasional error, right after this:
var id = generateRandom(rows * cols);
var el = document.getElementById(id.toString());
You can add this extra debug code:
// add this to detect what situation you get a missing element
if (!el) {
console.log("did not find id when: rows = " + rows + ", cols = " + cols");
}

Javascript: Passing Value of Tag to a Variable

Hope you can help me find a solution to this issue. I have a page with a number of anchor tags that contain an ID with a unique element. Here's a sample of the links:
<a href="#" class="button" id="widget_1"
onclick="$(this).parent().submit(); return false;">Button</a>
<a href="#" class="button" id="widget_2"
onclick="$(this).parent().submit(); return false;">Button</a>
<a href="#" class="button" id="widget_3"
onclick="$(this).parent().submit(); return false;">Button</a>
Below is the code that I tried to create to do collect the values in "id":
var num = [];
for (var i = 0; i<11; i++) {
num[i] = document.getElementsByTagName("id")[i].textContent;
if (num[i] == "widget_1"){ var y = "39.00"; return y;}
else if (num[i] == "widget_2"){ var y = "59.00"; return y;}
else if (num[i] == "widget_3"){ var y = "85.00"; return y;}
else { var y = "0";}
return y; }
What I'm trying to do is capture what's on id and use it to pass it to the array and if the contents match, then return the value of "y". For example, if I click on the second link, then 59.00 is returned. Any help that can be provided will be greatly appreciated.
Thanks,
Ridder
Another Approach
This approach also allows you to remove the onclick events in markup and improve readability, separating behavior from structure. (aka Separation of Concerns)
// put your prices on an array;
var prices = [39.0, 59.0, 85.0];
// match all widget(s) (aka anchors), add click handler.
$("[id^=widget]").click(function(element) {
// calculate the index into prices array based on anchor id.
var index = parseInt(this.id.substring(7)) - 1;
// get the pirce
var price = prices[index];
alert("Price is: " + price);
// here you could call
// this.$parent.submit();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Button
Button
Button
Pure Javascript
This version without jQuert. Enjoy!
Note: There are some limitations on old browsers (IE < 8 && FF3.0)
// put your prices on an array;
var prices = [39.0, 59.0, 85.0];
var elements = document.querySelectorAll('[id^=widget]');
Array.prototype.forEach.call(elements, function(element) {
var index = parseInt(element.id.substring(7)) - 1;
var price = prices[index];
element.onclick = function(event) {
alert(price);
};
});
Button
Button
Button
Extract just the number
var r = /\d+/;
var s = "add_to_cart_sku_ThisItemA1_CEB";
var index = s.match(r);
alert (index);
Extract a substring (for instance "ItemA1")
var code = "add_to_cart_sku_ThisItemA1_CEB";
var strIndex = code.substring(code.indexOf("Item"), code.lastIndexOf('_'));
alert (strIndex);
if we can define the function :
function MatchID(id) {
var y = "0";
if (id == "widget_1") {
y = "39.00";
} else if (id == "widget_2") {
y = "59.00";
} else if (id == "widget_3") {
y = "85.00";
}
return y;
}
Button
use this
switch(document.getElementById(this.id)){
case "widget_1":
var value = "59.00";
break;
case "widget_2":
var value = "60.00";
break;
case "widget_3":
var value = "61.00";
break;
}
return value;
that is what you need to get the basic job done, now you just need to get the click to go there, if it is another page you will need to know how it was sent and how it is recieved
hope this helps.
document.getElementsByTagName should be given html tag name instead of id and than you can access its id attribute as document.getElementsByTagName("a")[i].id
your code should be as follow :
var num = [];
for (var i = 0; i<11; i++) {
num[i] = document.getElementsByTagName("a")[i].id;
if (num[i] == "widget_1"){ var y = "39.00"; return y;}
else if (num[i] == "widget_2"){ var y = "59.00"; return y;}
else if (num[i] == "widget_3"){ var y = "85.00"; return y;}
else { var y = "0";}
return y; }
document.getElementsByTagName("id") this line in your code is not correct because there's no tags in html that is called `.
To retrieve all of the <a> tags in your document, there's a property of the HTMLDocument interface which is referred to as the document object which represents the entire html document. To retrieve all of the <a> tags. use this.
document.links this method returns a collection of the <a> tags, you can access this collection just like you do an array. For example, to access the first child in that collection.
document.links[0].href to get its href value or to get its id, you do document.links[0].id . Hope this helps

Undefined is returned from appended array

I currently POST to my script:
process : edit
r1_person : 00008
r2_person : 00009
persons : 2
Which my script accepts:
if (process == 'edit') {
var persons_array = [];
for (i = 0; i < persons; i++) {
var test_push = pnvl(request.getParameter('r' + i + '_person'))
persons_array.push(test_push);
response.write(persons_array[i] + '\n');
}
}
I get back:
undefined
undefined
Where am I going wrong?
EDIT:
Solution: response.write() will not return correctly inside a for loop.
Try this:
pnvl(request.getParameter(eval('r' + i + '_person')))
you iterate from 0 to 1, you want this:
for(i = 1; i <= persons; i++)

Why is my Javascript not valid?

I have a div with ID 'adpictureholder', to which I dynamically add (or remove) images.
On Form submit I want to get SRC values of all these images within that DIV and put them to the value of one hidden input with ID 'piclinkslisttosubmit'. The thing is that my current Javascript does not function as if there is some syntax typo there, but I don't see where. Can anyone please have a quick look at it?
function copyonsubmit(){
var strump1 = '';
var i=0;
var endi = document.getElementById('adpictureholder').childNodes[].length - 1;
var images = document.getElementById('adpictureholder').childNodes[];
for (i=0;i<=endi;i++)
{
strump1 = strump1 + '|' + images[i].src;
}
document.getElementById('piclinkslisttosubmit').value = strump1;
}
Change childNodes[] to simply childNodes.
You don't need to specify that a variable you're referencing is an array by adding brackets.
Your javascript isn't valid because you keep putting childNodes[] you can solve that by replacing childNodes[] with simply childNodes
function copyonsubmit(){
var strump1 = '';
var i=0;
var endi = document.getElementById('adpictureholder').childNodes.length - 1;
var images = document.getElementById('adpictureholder').childNodes;
for (i=0;i<=endi;i++)
{
strump1 = strump1 + '|' + images[i].src;
}
document.getElementById('piclinkslisttosubmit').value = strump1;
} ​
You shouldn't use [] when reading a property value:
var images = document.getElementById('adpictureholder').childNodes;
You can then get the length from the array, instead of reading the property again:
var endi = images.length - 1;
First off you don't need the [] after childNodes. that causes an error.
You also were forgetting that childNodes includes text nodes and would not work properly, because they did not all contain the src property. I've corrected that in the following example:
function copyonsubmit() {
var str = '';
var textbox = document.getElementById('piclinkslisttosubmit');
var i = 0;
var images = document.getElementById('adpictureholder').childNodes;
var numImages = images.length - 1;
var src = "";
for (i = 0; i < numImages; i++) {
if (images[i].tagName === "IMG") {
str += images[i].src + '|';
}
}
str = str.slice(0, -1); // cut off the final |
textbox.value = str;
}
http://jsfiddle.net/NWArL/2/
Secondly you could write this really simply with jQuery.
var str = "";
$("#apictureholder").children("img").each(function() {
str += $(this).attr("src") + "|";
})
$("#piclinkslisttosubmit").val(str);
Third off make sure to check your console for errors. It was very clear when I ran this code on JSFiddle that it had a problem.
Finally, what exactly are you trying to do?
Change childNodes[] to childNodes and rest looks fine to me,
Read about childNodes
Try,
function copyonsubmit(){
var strump1 = '';
var i=0;
var endi = document.getElementById('adpictureholder').childNodes.length - 1;
var images = document.getElementById('adpictureholder').childNodes;
for (i=0;i<=endi;i++)
{
strump1 = strump1 + '|' + images[i].src;
}
document.getElementById('piclinkslisttosubmit').value = strump1;
}
You said you were using jQuery, but you presented us with vanilla Javascript. I took the liberty of converting your code to jQuery and cleaning it up a bit. The others have already identified your problem, though.
function copyonsubmit() {
var strump1 = '';
var images = $("#adpictureholder")[0].childNodes;
for (var i = 0; i < images.length; i++) {
strump1 += '|' + images[i].src;
}
$('#piclinkslisttosubmit').val(strump1);
}​

Categories

Resources