Foreach loop javascript failing - javascript

Why does this each statement cause my code to break? Also do I have to set an index with javascript?
var email = [];
email['update'] = true;
email['e_case_id'] = $("#e_case").val();
var i = 0;
$.each($('.rowChecked'), function() {
email['e_attachments'][i] = $(this).attr('id');
i++;
});

Firstly, email should be an object literal, not an array literal:
var email = {};
Secondly, you didn't define email['e_attachments'] before you tried to use it. This is likely what's prevent it from working. Try adding
email['e_attachments'] = [];
Before the $.each.
You can use $.map in this circumstance, btw. That is:
email['e_attachments'] = $.map($('.rowChecked'), function (el) {
return $(el).attr('id');
});
Instead of your $.each. Or better yet:
email['e_attachments'] = $('.rowChecked').map(function () {
return $(this).attr('id');
}

Related

Javascript: call object method using string only

This code doesn't work.
var Modal = {
init: function() {
console.log("test");
}
}
var objMethod = "Modal.init";
window[objMethod]();
I saw some answers that it can be called using this but I want to know how it can be called without using the object.
Modal["init"]();
Thank you!
To call a namespaced function, you need to use a multidimensional array. In this case it would be window['Modal']['init'](), which can also be expressed by splitting the objMethod string and using array indices:
var arr = objMethod.split(".");
window[arr[0]][arr[1]]();
var Modal = {
init: function() {
console.log("test");
}
}
var objMethod = "Modal.init";
var arr = objMethod.split(".");
window[arr[0]][arr[1]]();

How can I put the results in an array after use each in javascript?

Hi I have this function:
changeTarea: function() {
var self = this;
$("#select_tarea_id").change(function() {
var id_tarea = $("#select_tarea_id").val();
$.each(self.objTareasFlot, function(index,value) {
for(var i = 0; i < value.length; i++) {
if(value[i].Id == id_tarea) {
self.objTareasFlotFinal['id']=value[i].Id;
self.objTareasFlotFinal['id_pro']=value[i].Id_proyecto;
self.objTareasFlotFinal['tarea']=value[i].nombre_tarea;
self.objTareasFlotFinal['porcentaje']=value[i].porcentaje;
console.info(self.objTareasFlotFinal);
}
}
});
});
}
And the function print :
But I need the 3 results in one array
for example :
How can I do that with that function? Sorry for my english I did try to explain of the better way
You can declare an array and push populated object into it. Something like this:
changeTarea: function(){
var self = this;
var container[];
$("#select_tarea_id").change(function() {
var id_tarea = $("#select_tarea_id").val();
$.each(self.objTareasFlot, function(index,value) {
for(var i = 0; i < value.length; i++){
if(value[i].Id == id_tarea){
self.objTareasFlotFinal['id']=value[i].Id;
self.objTareasFlotFinal['id_pro']=value[i].Id_proyecto;
self.objTareasFlotFinal['tarea']=value[i].nombre_tarea;
self.objTareasFlotFinal['porcentaje']=value[i].porcentaje;
console.info(self.objTareasFlotFinal);
container.push(self.objTareasFlotFinal);
}
}
});
});},
Create an array variable var result = []; inside your function.
Within your loop push() the objects into it;
results.push(self.objTareasFlotFinal);
var newArray = [];
self.objTareasFlotFinal['id']=value[i].Id;
self.objTareasFlotFinal['id_pro']=value[i].Id_proyecto;
self.objTareasFlotFinal['tarea']=value[i].nombre_tarea;
self.objTareasFlotFinal['porcentaje']=value[i].porcentaje;
newArray.push(self.objTareasFlotFinal);
// console.log should show the results
console.log(newArray);
If this array is meant to be global and accessible outside the function, you might want to define newArray outside the function first and remove the var from it within the function.
Then every time somebody runs the function, a new object is added to the array.
Alternatively, you could just return the array as the final value:
var newArray = [];
self.objTareasFlotFinal['id']=value[i].Id;
self.objTareasFlotFinal['id_pro']=value[i].Id_proyecto;
self.objTareasFlotFinal['tarea']=value[i].nombre_tarea;
self.objTareasFlotFinal['porcentaje']=value[i].porcentaje;
newArray.push(self.objTareasFlotFinal);
return newArray;

Javascript return variables from each function

Looping through children elements using each.
var divHeights = [];
$('#parent').children('div').each(function () {
divHeights.push(this.clientHeight);
});
alert(divHeights); // fails
How can I return the divHeights variable?
I've tried
var hts = ('#parent').children('div').each(function () { ...
but obviously that won't work.
You can do this in better way using .map() like:-
var divHeights = $('#parent').children('div').map(function () {
return this.clientHeight || 0;
}).get();
DEMO FIDDLE
The divHeights variable is available all the time. You can just assign it to a variable whenever you want:
var hts = divHeights;
This will just be another reference to the array, so you can do that any time after the array is created, even before you have put any values into it:
var divHeights = [];
var hts = divHeights;
$('#parent').children('div').each(function () {
divHeights.push(this.clientHeight);
});
You can of couse just use the variable divHeights instead of the variable hts when you want to use the result, or just use the variable hts instead of divHeights from start.
You could make it into a function like this:
function getHeights() {
return $('#parent div').map(function() {
return this.clientHeight;
});
}
Then you can just call the function wherever you like to get the array contents.

Prototype: observing 2 elements and pass different parameters?

CI have this code:
for(var i = 0; i < toObserve.length; i++) {
var elems = toObserve[i].split('###');
var elementToObserve = elems[0];
var imageToUse = elems[1];
$(elementToObserve).observe('click', respondToClick);
}
function respondToClick(event) {
var element = event.element();
}
In the respondToClick function I need a different image (imageToUse) for each elementToObserve. How can I do that? Can I pass a param or something?
Thanks!
Addition: I tried what Diodeus suggested, but it seems that only the last passed parameter is used, when any of the elements I observe is clicked. Whats wrong or is the way I want to do it not the right one?
Use an anonymous function:
$(elementToObserve).observe('click', function(event) {
var yourVar = "moo";
respondToClick(event,yourVar)
});
Use the specialised bindAsEventListener.
$(elementToObserve).observe('click',
respondToClick.bindAsEventListener(imageToUse)
);
The bound arguments will then be passed after the event parameter.
function respondToClick(event, imageToUse)
{
var element = event.element();
element.src = imageToUse;
}
I got this to work by simply assigning my variable to the element object:
elementToObserve.imageToUse = imageToUse;
Then in the observer function:
function respondToClick(event) {
var imageToUse = event.target.imageToUse;
}
I haven't realized any drawbacks to this.

Javascript array is undefined... and I'm not sure why

I'm trying to translate a PHP class into JavaScript. The only thing I'm having trouble with is getting an item out of an array variable. I've created a simple jsfiddle here. I cannot figure out why it won't work.
(EDIT: I updated this code to better reflect what I'm doing. Sorry for the previous mistake.)
function tattooEightBall() {
this.subjects = ['a bear', 'a tiger', 'a sailor'];
this.prediction = make_prediction();
var that = this;
function array_random_pick(somearray) {
//return array[array_rand(array)];
var length = somearray.length;
var random = somearray[Math.floor(Math.random()*somearray.length)];
return random;
}
function make_prediction() {
var prediction = array_random_pick(this.subjects);
return prediction;
}
}
var test = tattooEightBall();
document.write(test.prediction);
​
Works fine here, you are simple not calling
classname();
After you define the function.
Update
When you make a call to *make_prediction* , this will not be in scope. You are right on the money creating a that variable, use it on *make_prediction* :
var that = this;
this.prediction = make_prediction();
function make_prediction() {
var prediction = ''; //initialize it
prediction = prediction + array_random_pick(that.subjects);
return prediction;
}
You can see a working version here: http://jsfiddle.net/zKcpC/
This is actually pretty complex and I believe someone with more experience in Javascript may be able to clarify the situation.
Edit2: Douglas Crockfords explains it with these words:
By convention, we make a private that variable. This is used to make
the object available to the private methods. This is a workaround for
an error in the ECMAScript Language Specification which causes this to
be set incorrectly for inner functions.
To see the complete article head to: http://javascript.crockford.com/private.html
You never call classname. Seems to be working fine.
Works for me:
(function classname() {
this.list = [];
this.list[0] = "tiger";
this.list[1] = "lion";
this.list[2] = "bear";
function pickone(somearray) {
var length = somearray.length;
var random = somearray[Math.floor(Math.random()*length)];
return random;
}
var random_item = pickone(this.list);
document.write(random_item);
}());
Were you actually calling the classname function? Note I wrapped your code block in:
([your_code]());
I'm not sure what you're trying to accomplish exactly with the class structure you were using so I made some guesses, but this code works by creating a classname object that has instance data and a pickone method:
function classname() {
this.list = [];
this.list[0] = "tiger";
this.list[1] = "lion";
this.list[2] = "bear";
this.pickone = function() {
var length = this.list.length;
var random = this.list[Math.floor(Math.random()*length)];
return random;
}
}
var cls = new classname();
var random = cls.pickone();
You can play with it interactively here: http://jsfiddle.net/jfriend00/ReL2h/.
It's working fine for me: http://jsfiddle.net/YznSE/6/ You just didn't call classname(). If you don't call it, nothing will happen ;)
Make it into a self-executing function like this:
(function classname() {
this.list = [];
this.list[0] = "tiger";
this.list[1] = "lion";
this.list[2] = "bear";
function pickone(somearray) {
var length = somearray.length; //<---WHY ISN'T THIS DEFINED??
var random = somearray[Math.floor(Math.random() * length)];
return random;
}
var random_item = pickone(this.list);
document.write(random_item);
})();
var test = tattooEightBall();
document.write(test.prediction);
Should be:
var test = new tattooEightBall(); //forgot new keyword to create object
document.write(test.prediction()); // forgot parens to fire method
and:
this.prediction = make_prediction();
Should be:
this.prediction = make_prediction;

Categories