How to use Javascript replace to change var that was a number - javascript

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

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]]();

Adding properties to an object using function and bracket notation

I have an assignment on a basic javascript class that I'm taking and I can't seem to get this to work. I have this unit test that was given to me:
describe('AddSixthProperty', function() {
it('should add a food property with the value of bbq using bracket notation', function() {
expect(objects.addSixthProperty()['food']).to.equal('BBQ');
});
});
I was given an empty function:
// don't touch this line
var mysticalAnimal = objects.mysticalAnimal();
function addSixthElement(){
return
}
So I tried this:
var mysticalAnimal = objects.mysticalAnimal();
objects.addSixthProperty = function(){
mysticalAnimal['food'] = "bbq";
return mysticalAnimal["food"];
};
It doesn't work. Our test page doesn't pass that. Any help is greatly appreciated!
Thanks in advance!
You're returning mysticalAnimal['food'], and then the test tries to access ['food'] again, so it ends up accessing 'bbq'['food'], which is undefined. You need to just return mysticalAnimal, as well as get all your letter cases right. Here's a little proof of concept:
var objects = (function() {
var animal = { mystical: true };
return {
mysticalAnimal: function() { return animal; }
};
})();
var mysticalAnimal = objects.mysticalAnimal();
objects.addSixthProperty = function(){
mysticalAnimal['food'] = "bbq";
return mysticalAnimal;
};
var capturedAnimal = objects.addSixthProperty();
document.getElementById('result').innerText = capturedAnimal['food'];
<p id="result" />
Here is the function:
var mysticalAnimal = objects.mysticalAnimal();
objects.addSixthProperty = function(){
mysticalAnimal['food'] = "BBQ";
return mysticalAnimal;
};
// Test the function
console.log(objects.addSixthProperty()['food'])

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.

input into javascript function

I can't figure out how to have a javascript function which accepts a parameter correctly.
I can get the function working perfectly if I don't use a input parameter because I can do this:
var x = MyFunction;
But the moment I have to do this
var x = MyFunction(e);
Then it breaks.
I tried to work around this by setting the input parameter afterwards, but I can't get anything to work. How can I do this?
http://jsfiddle.net/TxMmG/
var MyFunction = function() {
var otherResult = function() {
alert("Hi");
},
input, objToAlert = function() {
return input;
};
return {
objToAlert: objToAlert,
input: input,
otherResult: otherResult
}
}();
var e1 = "test";
//var y = MyFunction(e); //this does not work if i add a parameter to function - moment i put parenthesis i get problems
var x = MyFunction;
x.input = e1; //also cant set the input here
x.objToAlert();
x.otherResult();
You put a () after the function definition, so the function is called and MyFunction is actually the object returned by the function, not the function itself.
Do like this:
var MyFunction = function() {
// ...
}; // No () here
The problem is that your function returns an object. Therefore you're assigning an object to a var y. You can not treat object as a function.

Referencing variable,it executes the function,however adding strings to the variable,returns function as string instead of value

The program is supposed to be a live search using php and javascript... where as you type it searches below. I just recently started learning javascript so sorry if my knowledge is limited...
$(document).ready(function () {
$('#results').append('<p>Started</p>');
var getText = (function () {
return document.getElementById('year').value;
});
var text = getText;
var getText1 = (function () {
return document.getElementById('class').value;
});
var text1 = getText1;
setInterval(function () {
var newText = getText;
var newText1 = getText1;
var loading = "search.php?year=" + newText + "&class=" + newText1;
$('#results').append(newText1);
if (text !== newText || text1 !== newText1) {
$('#results').load(loading);
$('#results').append('somethinghappened');
};
text = newText;
text1 = newText1;
}, 100);
});
so it works fine when i append newText1, however if i try to append "loading" it returns:
search.php?year=function () { return document.getElementById("year").value; }&class=function () { return document.getElementById("class").value; }
Can anyone explain what the difference between the two cases is and why a difference occurs? and possibly how to fix it so that it loads the correct URL
i searched and found: JavaScript: When assigning an anonymous function to a variable, function return value is not passed, rather the function as a string however didn't quite understand completely what it meant by passing two arguments, and when i tried to do something similar, it didn't work as expected...
Any help is appreciated and thanks in advance.
var newText = getText;
var newText1 = getText1;
You are assigning the functions getText and getText1 to the variables instead of executing them and assigning their return values. Try this instead:
var newText = getText();
var newText1 = getText1();
Or just:
var newText = document.getElementById('year').value;
var newText1 = document.getElementById('class').value;
try simply with
var getText = document.getElementById('year').value;
var getText1 = document.getElementById('class').value;
otherwise you will have only a reference to the function
You're not calling the functions, you're just referencing them.
To call them you need parens, like getText(). But why make them functions in this case? They're short and don't take parameters. If you want functions, make a single function that takes the string ID.

Categories