.innerHTML function Javascript - javascript

This is my code:
function text(var text)
{
var Value = document.getElementById("display").innerHTML;
var New = Value + text;
document.getElementById("display").innerHTML=New;
}
What it's supposed to do is get a string from when it's called, and then add that string to the end of a div element with the ID "display". I called it like this: text("hello");
The HTML of the webpage is a blank div element, and it stays blank even after the code is run. It worked when I did document.getElementById("display").innerHTML="hello!";, but isn't now. Thanks!

Don't use "var" for a function parameter - just listing it between the function parenthesis is enough. So change that function to:
function text(text)
{
var Value = document.getElementById("display").innerHTML;
var New = Value + text;
document.getElementById("display").innerHTML=New;
}
and it should work.

Take the var out of the function parameter: function text(text)...
BTW: don't name your parameter the same thing as your function - it's confusing.

And you can do it like this:
function text(inputText)
{
document.getElementById("display").innerHTML = document.getElementById("display").innerHTML +" "+ inputText;
}
:)

Related

How to make a js var in a function global to use it outside?

I want to make the "var id" in the function global. That i can use the value of it in the alert outside the function. Thats my code:
<script>
function myFunctionGetCode() {
var code = getInputVal('code'); //get value from Textinputfield from html
var con = "/";
var id = con+code;
}
alert(id);
</script>
You didn't specified what is your final goal or why are you trying to move id to a global scope, but you can do it by simple moving the var id (declaration) outside the function, then it will be global and accessible by all functions.
Obviously, the alert will show "undefined" since id only gets some value when the myFunctionGetCode() is called.
The code below shows this.
var id;
function myFunctionGetCode() {
var code = getInputVal('code'); //get value from Textinputfield from html
var con = "/";
id = con+code;
console.log(id)
}
alert(id);
function getInputVal(elemId){
return document.getElementById(elemId).value;
}
<input id="code"/>
<button onclick="myFunctionGetCode()">Get Id</button>
BUT if you want to throw the alert with the id value only when it gets some value then you should move the alert() inside the function. (You can still declare the id variable outside the function to let it global, or inside the function, as you currently have)
Open snippet to see:
//var id; -> You can still declare it here (as global)
function myFunctionGetCode() {
var code = getInputVal('code');
var con = "/";
var id = con+code; //or you can declare it here, but not global
alert(id);
}
function getInputVal(elemId){
return document.getElementById(elemId).value;
}
<input id="code"/>
<button onclick="myFunctionGetCode()">Get Id</button>
From your sample code I guess that you do not want to make your value global, but that you want to return a value - after all you are doing an operation inside your function that calculates a value from certain inputs.
So you would use the return keyword, and call the function to get the value:
<script>
function myFunctionGetCode() {
var code = getInputVal('code'); //get value from Textinputfield from html
var con = "/";
var id = con+code;
return id;
}
alert(myFunctionGetCode());
</script>
As a rule you do not want to make function variables global, since this means the value can be changed anywhere in your script or website, and that might lead to side effects and unexpected values in your function. If you need to pass something in use function parameters (or read from a text input like in your case), if you want to give back a result use return.
Can you move the alert inside the function or return the "id" value from the function instead?
You can make the variable global by doing something like:
window.your_namespace.id = value;
and then access the variable in the same way:
value = window.your_namespace.id
but its best not to pass data around using the global namespace.
You have to make var id to property of window object then you can access the id out side the function.
function myFunctionGetCode() {
var code = getInputVal('code'); //get value from Textinputfield from html
var con = "/";
window.id = 10;// Change to this
}
myFunctionGetCode();
alert(id);

How do you get html attributes in a javascript function with a variable element?

When a user clicks on an element in my HTML, I want a new tab to appear in their browser and the attributes of the element they clicked on to be printed in that window.
This is a typical element in the HTML:
<a id="d0e110" onclick="GetWordFile(this.id)" attr1="attr1_value" attr2="attr2_value" attr3="attr3_value">ElementContent</a>
There are many such elements. The UID is generated for each one during the XLST transformation ('id="{generate-id()}"').
This is my current javascript function:
<script>
function GetWordFile(id) {
var opened = window.open("");
opened.document.write();
}
</script>
If the last line of the function is "opened.document.write(id);", and an element is clicked, then the new window displays the correct UID for the clicked element. So the connection has been successfully established.
However, I cannot make any other attributes of the element appear in the new window. The following function, for example, produces a blank new window:
<script>
function GetWordFile(id) {
var opened = window.open("");
opened.document.write(attr1);
}
</script>
So does trying to get the attribute as a variable:
<script>
function GetWordFile(id) {
var opened = window.open("");
var a1 = getAttribute("attr1");
opened.document.write(a1);
}
</script>
I've also tried substituting inner HTML for document.write.
Can anyone identify what I am doing wrong and what my next steps should be?
You can pass this.attributes to the function, .filter() attributes that are not onclick, .map() the .value of the attributes to an array
<script>
function GetWordFile(attrs) {
attrs = [...attrs].filter(attr => {
return attr.name !== "onclick"
}).map(attr => attr.value);
console.log(attrs);
}
</script>
<a id="d0e110" onclick="GetWordFile(this.attributes)" attr1="attr1_value" attr2="attr2_value" attr3="attr3_value">ElementContent</a>
You need to call getAttribute() as a method of the element, which you can get using document.getElementById().
function GetWordFile(id) {
var el = document.getElementById(id);
var attr1 = el.getAttribute('attr1');
var opened = window.open("");
opened.document.write(attr1);
}
Instead of passing this.id as the function argument, you might consider just passing this. Why force the function to search for the element when you can just provide it directly? Then the function would be like:
function GetWordFile(el) {
var attr1 = el.getAttribute('attr1');
var opened = window.open("");
opened.document.write(attr1);
}
When you are loading a new window you are creating a new document that does not necessarily know that any other documents exist. In order for the document to know that any other documents exist you must pass in the desired information as a parameter so as mentioned above.
onclick="someFunction(this)" // which passes in the current scope
// you could then define someFunction like so to get the desired
// result
function someFunction ( htmlObject ) {
attributeList = htmlObject.attributes;
attributeArray = [...attributeList];//now can perform arrayfunctions
let a = "";
for (value in attributeArray) {
a += attributeArray[value].value + " "; // creates a string of
attributes
}
let s = window.open("");
s.document.write(a)}
Note you probably want to do some array filtering because it will return all attributes but the general principle works.

How to dynamically change the contents of a function using JavaScript

To help understand this the function is in the html page and it is generated, I cannot change the generated code:
function Update_qu7260() {
var newVal = ''
for( var idx = 0; idx < 2; idx++ )
{
var test
if( idx == 0 ) test = text7263
else if( idx == 1 ) test = text7265
if( test.matchObj ) newVal += test.leftSel + "-" + test.matchObj.rightSel + ","
}
newVal = newVal.substring( 0, newVal.length-1 )
VarQuestion_0001.set( newVal )
qu7260.hasBeenProcessed=false;
doImmFeedback('qu7260');
}
var qu7260 = new Object();
...
qu7260.updFunc = Update_qu7260;
var qObj=[qu7260];
Note in the above the number "7260", the numbers start at 1 so there are lots of them and each Update_###() will be different so I cannot re-write them with "hard wired" code. My code is in an external JavaScript file and is executed onLoad:
...
var updFunc = qObj[0].updFunc.toString();
if(updFunc.indexOf('doImmFeedback(')!=-1){
updFunc = updFunc.replace('doImmFeedback','doImmQuestionFeedback'); // do my function
updFunc = updFunc.replace('function ',''); // remove the word function
var funcName = updFunc.substr(0,updFunc.indexOf('(')); // get the function name e.g. Update_qu7260
updFunc = "window['" + funcName + "']=function" + updFunc.replace(funcName,'');
eval(updFunc);
}
...
When I change the eval() to alert() I can see the that it's correct, however, the eval() is not raising any errors and my function doImmQuestionFeedback is not being called. When I subsequently do an alert(qObj[0].updFunc.toString()) I see the original function.
It would seem that I have provided information that is too complex, so the following code is a better example:
function hi(){alert('hi');}
function changeHi(){
hi(); // I get an alert box with hi
newHi = "function hi(){alert('hi there');}"
eval(newHi);
hi(); // I get an alert box with hi
window.setTimeout('hi()',500); // I get an alert box with hi
}
window.setTimeout('changeHi()',500);
The following is the original question:
I have a predefined function that I did not create, however, I know it's name so I can get the function itself and then I change it by doing:
var funcText = window.updateFunc.toString();
funcText = funcText.replace('doSomeOtherFunction(','doMyFunction(');
How do I update the actual function so it will do all that it did before except it will now call doMyFuntion()?
The following is an example to help visualize what I want to do, the actual function I need to change is very complex. I have:
function updateFunc(whatToUpdate,true){
... - do lots of stuff.
var retVal = doSomeOtherFunction(whatToUdate);
... - do lots of stuff based on retVal
}
I need to change this to:
function updateFunc(whatToUpdate,true){
... - do lots of stuff
var retVal = doMyFunction(whatToUdate);
... - do lots of stuff based on retVal, I have had a chance to change retVal
}
Then the first thing my function will do is call doSomeOtherFunction() check/change the returned value and subsequently return the value to the updateFunc().
I have tried to manipulate the funcText above to:
funcText = 'window.updateFunc = function(...';
eval(funcText);
Without success.
This may be closed enough to what you are looking for.
Assuming you have this original function:
function originalFunc(val) {
// this function converts input string to upper case
return val.toUpperCase();
}
Now you want to override it to something either before or after you execute that function (in this example, we execute before, of course before or after doesn't matter in this case).
// we preserve orignal function
var originalFunc_save = originalFunc;
// now we override the original function with this block
var originalFunc = function(text) {
// lets call the orignal function
text = originalFunc_save(text);
// now do our custom thing
return text.split('').reverse().join('');
}
So our test should work.
var text = 'This is a test';
console.log(originalFunc(text));
Output:
TSET A SI SIHT
This method also works if you have to override functions inside a class. The only thing we have to be careful of is to choose a saved name that doesn't interfere with the original class code. _save may not be good enough, but you get the idea.
UPDATE: I'm updating this code above to use a string variable pointing to the original function. I think this is what the OP wanted.
Original code which defined by some library
function originalFunc(val) {
// this function converts input string to upper case
return val.toUpperCase();
}
Now we use the func string variable to point to that function and execute it.
var text = 'This is a test';
var func = 'originalFunc';
text = window[func](text);
console.log(text);
Output: Of course we get the original intended result because we haven't overridden it.
THIS IS A TEST
Now we write our code to override the original function behavior using a string pointing to the function.
// let's define a new function string
var funcSaved = func + '___saved';
// now preserve the original function code
window[funcSaved] = window[func];
// override the original function code block
window[func] = function(text) {
// lets call the orignal function
text = window[funcSaved](text);
// now do our custom thing
return text.split('').reverse().join('');
}
// let's test the code
text = 'This is a test';
text = window[func](text);
console.log(text);
Output:
TSET A SI SIHT
You can make a clone of updateFunc function, edit it at your discretion and work with it in what follows.
function updateFunc(whatToUpdate, param){ // the initial function
...
var retVal = doSomeOtherFunction(whatToUpdate);
return retVal;
}
// formation of unnamed function as string
var newfunc = updateFunc.toString().replace('function updateFunc', 'function ').replace('doSomeOtherFunction(', 'doMyFunction(');
function doMyFunction(whatToUpdate){ // your new function, just for example
console.log(parseInt(whatToUpdate) * 10);
}
var newUpdateFunc;
// declaring new version of 'updateFunc' function
// which is stored in 'newUpdateFunc' variable
eval("newUpdateFunc = " + newfunc);
newUpdateFunc(3); // outputs '30'
I believe this is a valid use case for the forgotten JavaScript with feature.
Basic idea: you call original updateFunc supplying your own version of doSomeOtherFunction to it using with namespace injection:
function updateFunc(whatToUpdate,true){
... - do lots of stuff.
var retVal = doSomeOtherFunction(whatToUdate);
... - do lots of stuff based on retVal
}
function patchUpdateFunc() {
var original_doSomeOtherFunction = window.doSomeOtherFunction;
var original_updateFunc = window.updateFunc;
function doMyFunction() {
// call original_doSomeOtherFunction() here,
// do your own stuff here.
};
window.updateFunc = function() {
with ({doSomeOtherFunction: doMyFunction}) {
return original_updateFunc.apply(this, arguments);
}
}
}
patchUpdateFunc();
I think you are going at this way too complicated.
If you only have doMyFunction and doSomeOtherFunction to switch between, you could just create a flag somewhere telling you to use one or the other when used in an if-statement.
If you want to call a function with a name you do not know beforehand and you only get a name during runtime, you could either accept the function to call as a parameter or accept the name of the function as a parameter and call it like so: var retVal = window[functionName](); (assuming functionName is a property of the window object).
I would highly recommend directly accepting a function as a parameter since the function may not be defined in a global scope.
EDIT:
After your clarification, I think, I can give you a satisfying answer:
if you have a string like var functionString = "function updateFunc(whatToUpdate){var retVal = doMyFunction(whatToUpdate);}";
You can define a function using a Function object:
window.updateFunc = new Function("whatToUpdate", "return (" + functionString + ")(whatToUpdate)");
This will replace the already existing function and you can give it any valid function string you want as long as you know and specify the arguments.
If I understood correctly, you want to override the external function. You can achieve that with the following code
//Someone else's function
function externalFunction(foo){
return "some text";
}
//Your function
function myFunction(value){
//Do something
}
//Override
var externalFunction = (function(){
var original = externalFunction; //Save original function
return function(){
var externalFunctionReturnValue = original.apply(this, arguments);
return myFunction(externalFunctionReturnValue);
}
})();
I strongly sugest not to use eval, but since you want to parse javascript from string:
function hi(){alert('hi');}
function changedHi(){
hi(); // I get an alert box with hi
newHi = "window['hi'] = function(){alert('hi there');}"
eval(newHi);
hi(); // I get an alert box with hi there
window.setTimeout('hi()',500); // I get an alert box with hi there
}
window.setTimeout('changedHi()',500);
UPDATE:
This code snippet works which is your original code:
<script type="text/javascript">
function doImmFeedback(foo){
console.log("DoImmFeedback: " + foo);
}
function Update_qu7260() {
console.log("Some code")
doImmFeedback('qu7260');
}
</script>
<script type="text/javascript">
var qu7260 = new Object();
qu7260.updFunc = Update_qu7260;
var qObj=[qu7260];
var updFunc = qObj[0].updFunc.toString();
if(updFunc.indexOf('doImmFeedback(')!=-1){
updFunc = updFunc.replace('doImmFeedback','doImmQuestionFeedback'); // do my function
updFunc = updFunc.replace('function ',''); // remove the word function
var funcName = updFunc.substr(0,updFunc.indexOf('(')); // get the function name e.g. Update_qu7260
updFunc = "window['" + funcName + "']=function" + updFunc.replace(funcName,'');
console.log(updFunc);
eval(updFunc);
}
function doImmQuestionFeedback(foo){
//Your function
console.log("doImmQuestionFeedback: " + foo);
}
Update_qu7260(); //This executes your doImmQuestionFeedback
</script>
So if your function isn't running, your function isn't in the global scope, or something else is happening, and we can't know if don't have any more info. Check your developer's console for javascript errors.

JavaScript function writing

This is what im doing:
1.
function getVal() {
var asd = document.getElementById("nomyape").value
}
getVal()
asd (to check if the var has something)
asd is undefined
pd: "nomyape" has a value , if i do document.getElementById("nomyape").value I get the value, thats why i know im pretty close
What i would like to make its a function that gets 6 diferents values from differents id, so when i call it i can gather all the form data
Thank you in advance
var values=[];
var ids=['nomyape_!','nomyape_2',...];
function getVals(){
for(i in ids){
values.push(
document.getElementById(ids[i]).value
);
}
}
use a for loop to store all values in the values array.
you can do like this. You need to remove var inside function which is making it a local variable.
var asd;
function getVal (){
asd=document.getElementById("nomyape").value
}
You should return the value from your function and assign it to a variable.
function getVal (elementId) {
return document.getElementById(elementId).value;
}
var a = getVal("id_of_element1");
var b = getVal("id_of_element2");
In your version of the code you create a local variable in the function that is only visible in the function.
Assuming all of your element's have id attributes, you could pass the element id into the function to get the value of each input.

How to get selector's variable on Onclick

When a selector is assigned to a variable, I need to get that variable name on onclick I have created a Fiddle as an example
var $main_img1 = $("<div/>").addClass('add1').appendTo($('#main_container'));
var $main_img2 = $("<div/>").addClass('add2').appendTo($('#main_container'));
$main_img1.click(function()
{
get_id()
});
$main_img2.click(function()
{
get_id()
});
function get_id(event)
{
console.log($(this))
alert('i need to get selector variable on click')
}
Output should be $main_img1 and $main_img2 when I click on the corresponding div
Here is a solution, but not sure how you are going to use it
Used Array to get the variable name.
JS
var arr = new Array();
arr[0] = '$main_img1';
arr[1] = '$main_img2';
var $main_img1 = $("<div/>").addClass('add1 add').appendTo($('#main_container'));
var $main_img2 = $("<div/>").addClass('add2 add').appendTo($('#main_container'));
$main_img1.click(function()
{
get_id($(this))
});
$main_img2.click(function()
{
get_id($(this))
});
function get_id(event)
{
alert(arr[$('.add').index(event)]);
}
Update : No array needed.
function get_id(event)
{
///var temp = '$main_img' + (parseInt($('.add').index(event)) + 1);
var temp = '$main_img' + (parseInt($('#main_container > div').index(event)) + 1);
alert(temp);
console.log(eval(temp));
}
Updated DEMO
I suggest a workaround.. see if it helps you. Add a hidden element inside the corresponding divs and add the variable names as text to it. I slightly modified your method get_id() to get the variable name from your divs hidden element.
function get_id()
{
console.log($(this))
var selVar= $(this).parent().find('input:hidden:first').text();
alert('selector variable' + selVar);
}
this will work for you.
You could maybe guessing from the class of the element you click on it and use reflexivity.
To know the element you click on it, just use event.target where event is a variable passed in the click function. Look at this fiddle for an example.
The get_id method now looks like this:
function get_id(event) {
console.log(event.target)
}
The value returned by event.target is the same as the value returned by the variable you declare it ($main_img1 or $main_img2).

Categories

Resources