I'm trying to set properties of some elements through a for loop, but am confused about the implementation.
Here is the code:
var fiArray = new Array('name','address','address2','phone','fax','misc1','misc2');
function disableFields(){
for(i=0,x=fiArray.length; i < x; i++){
var disEl = "$('formID')."+fiArray[i];
disEl.disabled=true;
}
}
I've tried every permutation of changing the disEl var, not using a var, concatenating different parts of the disEl string; nothing seems to work.
I know I'm missing something simple and fundamental here...
p.s. using prototype
var disEl = $('formID')[fiArray[i]];
Related
Hi I just can't figure this one out.
I need to use the window["evaluate string into js object"] because I am converting a web Application into a ChromeOS Chrome app and they do not let you use eval() to do their content security policy.
My problem is that for basic varibles it is fine, example:
var a = "foo";
var b = window["a"];
This will put "foo" into b no problem. But as soon as I have an object (both global or local) it doesn't work, so if 'a' was an object the code would like something like this:
a.test = "foo";
var b = window["a.test"];
That will not work.
Is there a reason for this? I can't seem to find much info on window[] in general so wondering if anyway has any insight or at least can point me in the right direction to look.
Thanks
window[] doesn't work on namespaced functions, so if you try to evaluate window['a.test'] it would fail. A proper alternative is to use window['a']['test']. In case you're indefinite of number namespaced objects you're going to use, you can create a simple function that would split the string from . and create a window object for each part. Example :
var str = 'namespace.service.function';
var parts = str.split(".");
for (var i = 0, len = parts.length, obj = window; i < len; ++i) {
obj = obj[parts[i]];
}
console.log(obj);
I have a question regarding variables in Javascript.
When I assign a var to a ID I do it like this:
var x = document.getElementById("div_name");
But I would like to make a variable which consists of multiple 'divs'.
I thought this might work but I does not:
var x = document.getElementById("div_name"),document.getElementById("div_name2");
Can someone please help me find the right code syntax and explain why the syntax I tried is incorrect.
So, If you just want them as a list of div's you could do this:
var x = [document.getElementById("div_name"),document.getElementById("div_name2")];
Just wrap them up with [].
If your var should contain more than one object (div in your case), then you need to have more variable or, better, an array.
You can create yor array by using following code.
var x = [document.getElementById("div_name"), document.getElementById("div_name2")];
This is due to the fact that different DIVs in the DOM page are different objects...
There is no such variable that is defined as:
var x = somthing, somesthingElse
You need to chose a variable that can store a collection of "things". In your case the Array is an ideal choice:
var x = [document.getElementById("div_name"),document.getElementById("div_name2")];
The brackets at the beginning and end of the expression are the syntax to declare a variable.
In addition to using Array, you can also store your divs in an Object
var divs = {
div1: document.getElementById("div_name"),
div2: document.getElementById("div_name2")
};
Thus, you could give a convenient name to your divs, but still pass them around as you please:
divs.div1;
divs.div2;
Or loop through them like so:
for (div in divs) {
console.log(divs[div]);
};
Knowledge: First week Javascript
I am trying to learn real javascript and avoid jquery at all cost. Now I am I recently learned that id's can be style easily but not classes. In order to style a class I need to loop through the dom for the class. My original code works, however my new one does not. Best practices aside for a moment, I am trying to learn how this works regardless if it is a perfect solution or not.
Problem specifics: In my new code I stored the two get functions in keys within an associative array. So I have objects which I would like my for loop to understand. I am trying to make it work like my first code.
What I tried: Honestly, I read something about squared bracket notation and how it can be useful. I felt a bit overwhelmed to be honest. What I tried was:
source[_class][i]
Maybe _class is undefined even though I defined it. I specified what class contains. Honestly im lost and would appreciate some help and of course I welcome best practice advice as well.
I want to be a better programmer and I would appreciate some insight. I dont want to start with jquery.
My experiment:
setTimeout(function() {
var source = {_id: document.getElementById('box'),
_class: document.getElementsByClassName('hint')};
for (var i = 0; i < source[_class].length; i++) {
source[_class + i].style.opacity = '0';
console.log(i);
}
}, 1000);
My original working code:
// setTimeout(function() {
// var divs = document.getElementsByClassName('hint');
// for (var i = 0; i < divs.length; i++) {
// divs[i].style.opacity = '0';
// console.log(i);
// }
// }, 1000);
Use source._class.length instead of source[_class].length and source._class[i] instead of source[_class + i]:
for (var i = 0; i < source._class.length; i++) {
source._class[i].style.opacity = '0';
console.log(i);
}
source is an object and has a property _class. You can access properties either as source._class or as source['_class'].
The property source._class is an collection of DOM nodes itself so it can be accessed like an array. You can access array elements like this: array[index].
So you have both an object with properties and an array with elements. You need to access their contents appropriately.
Styling should be done with css, not loops, because using css is an order of magnitude faster.
Create css class definitions for your set of styles and then simply change the name of the class on your elements to change their style.
Also, look into using css selectors to query the DOM. This is done with querySelector for a single element, or querySelectorAll for a set of elements. Note that jQuery wraps this functionality and that is where the name is derived.
For your specific example, the problem was with accessing the array, instead of adding the i index, you need to reference the array, and you also need to make sure you are using a string index or a dot notation (such as source._class) in order to reference that object's property
for (var i = 0; i < source['_class'].length; i++) {
source['_class'][i].style.opacity = '0';
console.log(i);
}
You missed a square bracket and it's text not a variable:
source[_class + i].style.opacity = '0';
should be
source["_class"][i].style.opacity = '0';
First question ever, new to programming. I'll try to be as concise as possible.
What I want to do is to create a bunch of children inside a selected div and give each of them specific html content (from a predefined array) and a different id to each child.
I created this loop for the effect:
Game.showOptions = function() {
var i = 0;
Game.choiceElement.html("");
for (i=0; i<Game.event[Game.state].options.length; i++) {
Game.choiceElement.append(Game.event[Game.state].options[i].response);
Game.choiceElement.children()[i].attr("id","choice1");
}
};
Using the predefined values of an array:
Game.event[0] = { text: "Hello, welcome.",
options: [{response: "<a><p>1. Um, hello...</p></a>"},
{response: "<a><p>2. How are you?</p></a>"}]
};
This method does not seem to be working, because the loop stops running after only one iteration. I sincerely have no idea why. If there is a completely different way of getting what I need, I'm all ears.
If I define the id attribute of each individual p inside the array, it works, but I want to avoid that.
The idea is creating a fully functional algorithm for dialogue choices (text-based rpg style) that would work with a predefined array.
Thanks in advance.
The problem with your loop as I see it could be in a couple different places. Here are three things you should check for, and that I am assuming you have but just didn't show us...
Is Game defined as an object?
var Game = {};
Is event defined as an array?
Game.event = new Array();
Is Game.state returning a number, and the appropriate number at that? I imagine this would be a little more dynamic then I have written here, but hopefully you'll get the idea.
Game.state = 0;
Now assuming all of the above is working properly...
Use eq(i) instead of [i].
for (var i = 0; i<Game.event[Game.state].options.length; i++) {
Game.choiceElement.append(Game.event[Game.state].options[i].response);
Game.choiceElement.children().eq(i).attr("id","choice" + (i + 1));
}
Here is the JSFiddle.
This is very basic I'm sure to JavaScript but I am having a hard time so any help would be appreciated.
I want to call a function within a for loop using the mouseDown event occurring within an object's second child node. The part italicized is my attempt to do this. The swapFE function is still a work in progress by the way. And one more thing is when I put the italicized part in the swapFE function everything works properly but when I put it in the for loop it doesn't all show up. I don't know why. I am basically trying to swap French phrases for English ones when I click the phrase with my mouse.
function setUpTranslation() {
var phrases = document.getElementsByTagName("p");
var swapFE = document.getElementsByTagName("phrase");
for (i = 0; i<phrases.length; i++) {
phrases[i].number = i;
phrases[i].childNodes[1].innerHTML = french[i];
*phrases[i].childNodes[1].onMouseDown = swapFE;*
}
}
/* see "function_swapFE(phrase,phrasenum);" below. The expression to call function swapFE
is located underneath "function swapFE(e)" because although the directions said to put the
"run swapFE" within the for loop it did not work properly that's why I put it beneath the
"function swapFE(e)".*/
function swapFE(e) {
var phrase = eventSource(e);
var phasenum = parseInt(1) = [1].innercontent.previousSibling;
phrase.node.previousSibling.onmousedown=swapFE
function_swapFE(e)(phrase,phrasenum);
}
}
If you have questions let me know.
Thanks for your help.
With this, you are creating a local variable named swapFE;
var swapFE =
document.getElementsByTagName("phrase");
Then with this you are setting this var as a mouseDown
phrases[i].childNodes[1].onMouseDown =
swapFE;*
That's not right... onMouseDown should be set to a function name, not a local variable of that name. So you should probably rename the local var to something else. That will at least get you closer to a solution.
I can only make a couple of guesses at what might be failing with your source code. Firstly, the following code assumes that all <p> tags have at least 2 child elements:
for (i = 0; i<phrases.length; i++) {
phrases[i].number = i;
phrases[i].childNodes[1].innerHTML = french[i];
*phrases[i].childNodes[1].onMouseDown = swapFE;*
}
If any <p> tags on your page have less than 2 child elements, an error will be thrown and script execution will halt. The best solution for this would be to add a class attribute to each <p> tag that will contain the elements you're looking for. Alternatively, you could just check for the existence of the second childnode with an if statement. Or you could do both.
Secondly, like all events, onmousedown should be declared in lowercase. Setting onMouseDown will not throw an error, but instead create a custom property on the element instead of attaching an event handler.
Finally, the following code:
var swapFE = document.getElementsByTagName("phrase");
will locally override the global function swapFE for that function, replacing it with a variable instead.
This is how I might write your setupTranslation function:
function setUpTranslation() {
var phrases = document.getElementsByTagName("p");
// rename the swapFE var as outlined below
var swapFENodes = document.getElementsByTagName("phrase");
var cNode; // set up an empty variable that we use inside the loop
for (i = 0; i<phrases.length; i++) {
/* Check for the existence of the translationPhrase class
in the <p> tag and the set the cNode var to childNodes[1]
and testing for its existence at the same time */
if (cNode.className != "translationPhrase"
|| !(cNode = phrases[i].childNodes[1]))
continue; // skip to the next iteration
phrases[i].number = i;
cNode.innerHTML = french[i];
cNode.onmousedown = swapFE; // Changed onMouseDown to onmousedown
}
}