Javascript return variables from each function - javascript

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.

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 to use Javascript replace to change var that was a number

I'm missing something very basic here, I think!
$(function() {
$('#zahlungsart_0').click(function() {
var gesamtsumme_neu = Number($('#gesamtsumme').attr('rel'))+6;
gesamtsumme_neu.toString;
gesamtsumme_neu.replace('.',',');
console.log(gesamtsumme_neu);
$('#gesamtsumme').text(gesamtsumme_neu);
});
Error: TypeError: gesamtsumme_neu.replace is not a function
Thanks in advance for any help!
$(function() {
$('#zahlungsart_0').click(function() {
var gesamtsumme_neu = Number($('#gesamtsumme').attr('rel'))+6;
gesamtsumme_neu = gesamtsumme_neu.toString();
gesamtsumme_neu = gesamtsumme_neu.replace('.',',');
console.log(gesamtsumme_neu);
$('#gesamtsumme').text(gesamtsumme_neu);
});
Assign the values of toString(), replace()
Also toString is a function
You have to call toString and reassign it to the variable; just like you have to do with replace. Like this:
$(function() {
$('#zahlungsart_0').click(function() {
var gesamtsumme_neu = Number($('#gesamtsumme').attr('rel'))+6;
gesamtsumme_neu = gesamtsumme_neu.toString();
gesamtsumme_neu = gesamtsumme_neu.replace('.',',');
console.log(gesamtsumme_neu);
$('#gesamtsumme').text(gesamtsumme_neu);
});
The two function don't change the variable you are calling them on but return a new variable.
toString() returns a string, so try this:
var q = gesamtsumme_neu.toString();
q = q.replace('.',',');
console.log(q);
// etc
toString is not a property, it's a function - toString(), thus should be called as such. You're also not changing the value of the variable you call it on - you need to assign the return value to [another] variable:
$(function() {
$('#zahlungsart_0').click(function() {
var gesamtsumme_neu = Number($('#gesamtsumme').attr('rel'))+6;
var newVal = gesamtsumme_neu.toString().replace('.',',')
console.log(newVal );
$('#gesamtsumme').text(newVal);
});

Adding the results of a function to an array

I have numerous input boxes that I'm trying to store the names of into an array. I'm using this currently to get the names:
var getImplementedNames = function (selector){
$(selector).each(function() {
console.log($( this ).attr('name').replace('imp-', ''));
});
}
console.log(getImplementedNames('[id^=imp]'));
This works, but now I'd like to add all the reslts to an array. I've tried;
var array = [getImplementedNames('[id^=imp]')];
console.log(array);
Which returns an undefined array.
I'm not sure of how this is supposed to be properly handled.
Use .map()
var getImplementedNames = function (selector) {
return $(selector).map(function () {
return $(this).attr('name').replace('imp-', '');
}).get();
}
usage
console.log(getImplementedNames('[id^=imp]'));
Read Return Value from function in JavaScript
Your function isn't currently returning anything. Try:
var getImplementedNames = function (selector){
return $(selector).map(function() {
return $( this ).attr('name').replace('imp-', '');
});
}
console.log(getImplementedNames('[id^=imp]'));

Variable in nested function returns undefined

The variable my_sound is declared in the first, outer function. So, I should be able to use it in the nested function. However the mouseout event produces no result. What am I doing wrong? Thanks for any help.
$(document).ready(function () {
var starting_pics = ["CN.gif", "EN.gif", "GN.gif"];
var starting_sounds = ["CN.mp3", "EN.mp3", "GN.mp3"];
var i = 0;
for (i = 0; i < starting_pics.length; i++) {
$("<img/>").attr("src", "images/" + starting_pics[i]).appendTo("#main").addClass("pics");
}
$("#main").on("click", ".pics", function () {
var i = $(this).index();
var my_sound =($("<audio/>").attr("src", "audio/" + starting_sounds[i])).load().get(0).play();
$("#main").on("mouseout", ".pics", function () {
$("my_sound").animate({ volume: 0 }, 1000);
});
});
});
The problem is probably that .play() doesn't return a jQuery object (or anything, for that matter, hence undefined).
Additionally, as the other comments have said, you don't want $('my_sound').whatever but rather just my_sound.whatever if it were a jQuery object, which it is not. So maybe you could try
var $my_sound = $("<audio />").attr("suchandsuch","etc");
$my_sound.load().get(0).play();
$my_sound.whatever();

Foreach loop javascript failing

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');
}

Categories