input into javascript function - javascript

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.

Related

Javascript Typedef Error when using parameters

What am I doing wrong, and how can one pass variables to a different function within the same wrapping variable/function.
Example:
function customFunctionWrap(){
this.myVar1 = 0;
this.getCurrentPosition = function(){
if (navigation.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){});
}
},
this.doSomething = function(){ // Works
//Do something, return
this.callWithParams(); //Works
},
//If I remove passing in 'value1',calling it elsewhere works
this.doSomethingWithParams = function(value1){
//Use value1
//Return
},
this.callWithParams = function(){
var value1 = 'xyz'; //Is a variable that changes based on some DOM element values and is a dynamic DOM element
this.doSomethingWithParams(value1); //THROWS TYPEDEF ERROR: this.doSomethingWithParams is not a function
this.getCurrentPosition();
}
};
var local = new customFunctionWrap();
local.doSomething(); //WORKS
I know there is another way to do it and then directly use customFunctionWrap.callWithParams(), but am trying to understand why the former approach is erroring out.
var customFunctionWrap = {
myVar1 : 0,
callWithParams : function(){
}
}
What JS sees:
var customFunctionWrap = (some function)()
returned function is fired, because the last (), so it has to yield/return something, otherwise, like in your code it is "returning" undefined.
So your given code does not work.
The very first fix is to delete last 2 characters from
var customFunctionWrap = (some function)()
to make it return constructor.

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

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.

Accessing data from text box

function testTask06()
{
var cipherText = document.getElementById('cipherTextBox').value;
var indexCharacter = document.getElementById('indexCharacterTextBox').value;
document.getElementById('plainTextBox').value = (decryptMessage(cipherText, indexCharacter, plainArray, cipherArray));
}
I want to get values from textbox called 'cipherTextBox' and 'indexCharacterTextBox', then use those values in my function decryptMessage and then display result in textbox 'plainTextBox'. It doesnt work but i'm wondering if it's because my function decryptMessage is wrong.
This basic example works
function foo() {
var cipherText = document.getElementById('cipherTextBox').value;
var indexCharacter = document.getElementById('indexCharacterTextBox').value;
document.getElementById('plainTextBox').value =
decryptMessage(cipherText, indexCharacter, [], []);
}
function decryptMessage(a, b) {
// dummy function
return a + b;
}
document.getElementById("button").addEventListener("click", foo, false);
There's probably something wrong with your decryptMessage function. We need to see that.

How do I run an object's method onEvent in javascript?

I just started using javascript and I'm missing something important in my knowledge. I was hoping you could help me fill in the gap.
So the script I'm trying to run is suppose to count the characters in a text field, and update a paragraph to tell the user how many characters they have typed. I have an object called charCounter. sourceId is the id of the text area to count characters in. statusId is the id of the paragraph to update everytime a key is pressed.
function charCounter(sourceId, statusId) {
this.sourceId = sourceId;
this.statusId = statusId;
this.count = 0;
}
There is one method called updateAll. It updates the count of characters and updates the paragraph.
charCounter.prototype.updateAll = function() {
//get the character count;
//change the paragraph;
}
I have a start function that is called when the window loads.
function start() {
//This is the problem
document.getElementbyId('mytextfield').onkeydown = myCounter.updateAll;
document.getElementbyId('mytextfield').onkeyup = myCounter.updateAll;
}
myCounter = new charCounter("mytextfield","charcount");
window.onload = start;
The above code is the problem. Why in the world can't I call the myCounter.updateAll method when the event is fired? This is really confusing to me. I understand that if you call a method likeThis() you'll get a value from the function. If you call it likeThis you are getting a pointer to a function. I'm pointing my event to a function. I've also tried calling the function straight up and it works just fine, but it will not work when the event is fired.
What am I missing?
Thanks for all the answers. Here's three different implementations.
Implementation 1
function CharCounter(sourceId, statusId) {
this.sourceId = sourceId;
this.statusId = statusId;
this.count = 0;
};
CharCounter.prototype.updateAll = function() {
this.count = document.getElementById(this.sourceId).value.length;
document.getElementById(this.statusId).innerHTML = "There are "+this.count+" charactors";
};
function start() {
myCharCounter.updateAll();
document.getElementById('mytextfield').onkeyup = function() { myCharCounter.updateAll(); };
document.getElementById('mytextfield').onkeydown = function() { myCharCounter.updateAll(); };
};
myCharCounter = new CharCounter('mytextfield','charcount');
window.onload = start;
Implementation 2
function CharCounter(sourceId, statusId) {
this.sourceId = sourceId;
this.statusId = statusId;
this.count = 0;
};
CharCounter.prototype.updateAll = function() {
this.count = document.getElementById(this.sourceId).value.length;
document.getElementById(this.statusId).innerHTML = "There are "+ this.count+" charactors";
};
CharCounter.prototype.start = function() {
var instance = this;
instance.updateAll();
document.getElementById(this.sourceId).onkeyup = function() {
instance.updateAll();
};
document.getElementById(this.sourceId).onkeydown = function() {
instance.updateAll();
};
};
window.onload = function() {
var myCounter = new CharCounter("mytextfield","charcount");
myCounter.start();
};
Implementation 3
function CharCounter(sourceId, statusId) {
this.sourceId = sourceId;
this.statusId = statusId;
this.count = 0;
};
CharCounter.prototype.updateAll = function() {
this.count = document.getElementById(this.sourceId).value.length;
document.getElementById(this.statusId).innerHTML = "There are "+this.count+" charactors";
};
function bind(funcToCall, desiredThisValue) {
return function() { funcToCall.apply(desiredThisValue); };
};
function start() {
myCharCounter.updateAll();
document.getElementById('mytextfield').onkeyup = bind(myCharCounter.updateAll, myCharCounter);
document.getElementById('mytextfield').onkeydown = bind(myCharCounter.updateAll, myCharCounter);
};
myCharCounter = new CharCounter('mytextfield','charcount');
window.onload = start;
I think you are having problems accessing your instance members on the updateAll function, since you are using it as an event handler, the context (the this keyword) is the DOM element that triggered the event, not your CharCounter object instance.
You could do something like this:
function CharCounter(sourceId, statusId) {
this.sourceId = sourceId;
this.statusId = statusId;
this.count = 0;
}
CharCounter.prototype.updateAll = function() {
var text = document.getElementById(this.sourceId).value;
document.getElementById(this.statusId).innerHTML = text.length;
};
CharCounter.prototype.start = function() {
// event binding
var instance = this; // store the current context
document.getElementById(this.sourceId).onkeyup = function () {
instance.updateAll(); // use 'instance' because in event handlers
// the 'this' keyword refers to the DOM element.
};
}
window.onload = function () {
var myCharCounter = new CharCounter('textarea1', 'status');
myCharCounter.start();
};
Check the above example running here.
The expression "myCounter.updateAll" merely returns a reference to the function object bound to "updateAll". There's nothing special about that reference - specifically, nothing "remembers" that the reference came from a property of your "myCounter" object.
You can write a function that takes a function as an argument and returns a new function that's built specifically to run your function with a specific object as the "this" pointer. Lots of libraries have a routine like this; see for example the "functional.js" library and its "bind" function. Here's a real simple version:
function bind(funcToCall, desiredThisValue) {
return function() { funcToCall.apply(desiredThisValue); };
}
Now you can write:
document.getElementById('myTextField').onkeydown = bind(myCounter.updateAll, myCounter);
You can:
function start() {
//This is the problem
document.getElementbyId('mytextfield').onkeydown = function() { myCounter.updateAll(); };
document.getElementbyId('mytextfield').onkeyup = function() { myCounter.updateAll(); };
}
In ASP.Net Ajax you can use
Function.createDelegate(myObject, myFunction);
I want to do something like this but simpler.
The idea is to have the user click on bolded text and have a text field appear where they can change all the values of a role-playing character. Then when the value is changed, have the text field disappear again replaced by the updated bolded text value.
I can do this already using an annoying text box alert. But I would rather have something similar to this below to replace all that.
I have searched for months and CMS is the closest to answering my question in the simplest way with a full html example. Nobody else on the net could.
So my question is, how do I do this?
I have multiple objects(characters) and need this.elementId to make this work.
I've modified this example but it breaks if I try to add to it.
html>
head>
title>Sandbox
/head>
body>
input id="textarea1" size=10 type=text>
script>
function CharCounter(sourceId, statusId)
{this.sourceId=sourceId;
this.statusId=statusId;
this.count=0;
}
CharCounter.prototype.updateAll=function()
{text=document.getElementById(this.sourceId).value
document.getElementById(this.statusId).innerHTML=text
}
CharCounter.prototype.start=function()
{instance=this
document.getElementById(this.sourceId).onkeyup=function ()
{instance.updateAll()}
}
window.onload=function ()
{myCharCounter=new CharCounter('textarea1', 'status')
myCharCounter.start()
}
/script>
/body>
/html>

Categories