I wanted to code simple function to change the title of the document.
First I tried this code:
<head>
<meta charset="utf-8">
<title>Zmeň mě!</title>
</head>
<body>
<input type="text" id="newTitle">
<button type="button" onclick="titleChange()">sub</button>
</body>
<script type="text/javascript">
var title, newTitle;
title = document.title;
newTitle = document.getElementById("newTitle").value;
function titleChange(newTitle) {
title = newTitle;
}
</script>
That didn't work so I was randomly changing it to this:
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Zmeň mě!</title>
</head>
<body>
<input type="text" id="newTitle">
<button type="button" onclick="titleChange()">sub</button>
</body>
<script type="text/javascript">
function titleChange(newTitle) {
document.title = document.getElementById("newTitle").value;
}
</script>
Why the second one works, but the first one doesn't?
Thank you so much for the answers.
Why the second one works, but the first one doesn't?
There are two parts to the problem:
Where you are getting the new value from.
Where you are assigning the value to.
Getting the new value
In
function titleChange(newTitle) {
title = newTitle;
}
you are getting the new value from the newTitle parameter. But looking at the callsite (onclick="titleChange()") you are never passing a value for the parameter.
Now, above the function you are defining a variable with the same name:
newTitle = document.getElementById("newTitle").value;
This doesn't have any effects for two reasons:
The parameter newTitle shadows the variable with the same name, thus the value of the variable is never read.
var foo = 42;
function bar(foo) {
console.log(foo);
}
bar(21); // logs 21, not 42
The assignment happens only once at page load. At this point in time the input field doesn't have a value yet. Changes to the field later on won't magically update the variable.
In your second example you are reading the input field value inside the event handler, i.e. you are getting the current input value at the moment the handler is executed.
Assigning the new value
JavaScript is a pass by value language. That basically means that if you assign the value of a variable or an object property to another variable, a copy of the value is created and assigned. There is no intrinsic connection between the new variable and the "source variable". Thus assigning to title won't affect document.title in any way.
Here is a simplified example:
var foo = 42;
var bar = foo;
bar = 21;
console.log(foo); // still 42, assinging to 'bar' doesn't change 'foo'
Directly assigning to document.title, as in your second example, works as expected.
you are starting with JavaScript?
document.title is type string.
> typeof(document.title)
"string"
So when you assign title = document.title; in your first example, you actually copy the string value.
When you are declaring the title variable in the first try you just stored it's current value in the variable. In the second one you are directly setting document.title to another value. With that approach you don't need to pass the function the newTitle varaible since you aren't using it anyways. Try:
function titleChange() {
document.title = document.getElementById("newTitle").value;
}
I think it can be about parameter. You gave newTitle parameter to your function when you defined it but you didn't use it while calling your function. You can try this code
function titleChange() {
var title, newTitle;
title = document.title;
newTitle = document.getElementById("newTitle").value;
title = newTitle;
}
Related
I am trying to make a web tool that takes user imputed values as a list of objects and a number of objects to randomly choose and then will print out the number of objects chosen from the list at random when the button is clicked. However i have not been able to get anything to print. I have tried to call the variables both with qoutes and without them and i still haven't gotten the compute to print any results in the final read only textbox. I think the issue is somewhere in my script functions but i cant figure out where and i've spent hours looking up syntax and possible issues to no avail. Ive tried to work with inner.html without success and the current method (document.getById....) is copied from http://www.mauvecloud.net/randomchooser.html that works to randomly choose one thing and print the result.
<html>
<style></style>
<head>
<title>Random Chooser</title>
<script>
Array.protoype.chooseFromArray() = function(){
var chosenIndex = Math.floor(Math.random() * ValueArray.length);
var elementPicked = ValueArray["chosenIndex"];
ValueArray.splice("chosenIndex",1);
return elementPicked;
}
function chooseRandomly(){
var ValueArray = document.getElementById("valuelist").value.split("\n");
var numItems = document.getElementById("items").value;
var ReturnArray = [];
for(i=0; i < numItems; i++){
var element = ValueArray.chooseFromArray();
ReturnArray.push("element");
}
document.getElementById("result").value = ReturnArray.toString();
}
</script>
<body>
Enter some values, one on each line, then click the choose button to pick randomly.
<form action onsubmit="return false;">
<textarea id="valuelist" rows="15" cols="60"></textarea>
<br>
<br>
Randomly choose <input type="number" id="items" > items
<br>
<input type="button" value="Choose" onclick="chooseRandomly();return false">
<br>
<br>
<input id="result" type="text" size="80" value readonly="readonly">
<br>
<br>
</form>
</body>
</html>
You're confused on a few JavaScript syntax points. I won't bother correcting the non-idiomatic style, you should read more about that here on your own once you understand the changes outlined below.
First, here's the cleaned up and fixed version so we can take a look at it together:
Array.prototype.chooseFromArray = function() {
var chosenIndex = Math.floor(Math.random() * this.length);
var elementPicked = this[chosenIndex];
this.splice(chosenIndex, 1);
return elementPicked;
}
function chooseRandomly() {
var ValueArray = document.getElementById("valuelist").value.split("\n");
var numItems = document.getElementById("items").value;
var ReturnArray = [];
for (var i = 0; i < numItems; i++) {
var element = ValueArray.chooseFromArray();
ReturnArray.push(element);
}
document.getElementById("result").value = ReturnArray.toString();
}
window.chooseRandomly = chooseRandomly;
First thing's first, to reference a function from HTML on JSFiddle you'll need it to be defined on the window. You don't normally need to do that, so you can mostly ignore that point.
Generally, you have several syntax errors.
Defining a property on an object (prototypes are objects (MDN)) happens just like variable assignment, so you just write object.<property_name> = value. You were calling chooseFromArray then assigning to that call (which is just invalid syntax).
When creating functions for prototypes, this will usually reference the object calling the function. In this case, any array calling chooseFromArray will have itself bound to the this reference inside the prototype function.
When accessing properties through the indexer you just pass the string. If it's a variable, you don't surround it with strings. Ex:
var chosenIndex = 123;
var elementPicked = this["chosenIndex"];
// This is the same as this.elementPicked;
var elementPicked = this[chosenIndex];
// This is what you want as you're accessing the `123` property on `this`
The same goes for passing variables to functions. You just pass the variable. Anything inside of 's, ' ` 's and "s are string literals and will not reference any variables.
I need to pass a value from html and use it to find a var in my Js, so according to the value in theId on my html I could use the var in my js. How can I do that?
HTML
<input id="Waist" type="checkbox" onchange="getToWork(this.id)" >Waist
<script> tag on HTML
function getToWork(theId){
usedCheckBox(theId);
}
myJs.js
function usedCheckBox(theId){
var temp1 = theId.name; - will be undefined
var temp2 = Waist.name; - will work
}
var Waist = {name:"bob",age:"17"}
The problem with your code is, you are not using document.getElementById as below:
JS:
document.getElementById("Waist").addEventListener("change",function(evt){
getToWork(this.id);
})
function getToWork(theId){
usedCheckBox(theId);
}
function usedCheckBox(theId){
console.log(theId);
console.log(Waist);
var temp1 = document.getElementById("Waist").val; // will return Waist
var temp2 = Waist.val(); // generate error, don't know what you want
}
var Waist = "change today!"
Fiddle:
https://jsfiddle.net/xLvzah8w/1/
I understood your question now and for that you should create one parent object as shown:
function usedCheckBox(theId){
var temp1 = parent[theId].name; // will return bob
console.log(temp1);
var temp2 = parent.Waist.name; // will return bob
console.log(temp2);
}
var parent = {
Waist : {name:"bob",age:"17"}
}
The reason why your code doesn't work is because you are trying to access property of a string. 'theId' is a string with value 'Waist' where Waist is an object so error occurs.
Updated fiddle: https://jsfiddle.net/xLvzah8w/2/
The correct way to proceed with this is:
In place of var temp1 = theId.val();
Use document.getElementById(theId).value
When you do: theId.val(), it makes sense that it's undefined. Calling getToWork(this.id) is sending a string, not an HTML element. Therefore calling .val() on a string is undefined.
If you're trying to get the text value stored in the checkbox element that was pressed, you need to change to ...
function getToWork(arg) {
console.log(document.getElementById(arg).value);
}
<input id="Waist" type="checkbox" value="INPUT_BOX" onchange="getToWork(this.id)"> Waist
You should avoid using the onclick attribute and rather listen for the event "js side" (addEventListener/attachEvent).
In the context of those eventhandlers, this generally represents the element the event listener has been attached to:
document.getElementById("Waist").addEventListener("change",getToWork);
function getToWork(){
usedCheckBox(this);
}
function usedCheckBox(elem){
var value = elem.value ;
}
I am wondering how I would create a variable on the click of a button, so I could make a random name generator, like this:
<input class="varValue" placeholder="Name to be generated">
<button class="createVar></button>
<script>
var createVar = document.querySelector(".createVar");
var varValue = document.querySelector(".varValue");
var nameNumber = 0;
var getValue = function(){
varValue.value = //new var with ascending values or something;
nameNumber = nameNumber + 1;
};
createValue.addEventListener("click", getValue(), false");
//then some Math.random using, nameNumber, anyway I'll figure it out
</script>
So how would I make the variables on the click of the button?
Also no jQuery please.
The function getValue() [which I don't see declared, so it should be declared somewhere] is in charge of any new logic attached to that event in this case.
To create and do something with those variables simply do it right inside that function.
I believe you meant createVar.addEventListener() and not createValue
Trying to pass i variable to test function that must change value:
<HTML>
<HEAD>
<TITLE> Welcome to my site</TITLE></HEAD>
<BODY>
<SCRIPT LANGUAGE="JAVASCRIPT">
var atl = new ActiveXObject("ATL.Object.1");
var i =6;
atl.test(i);
document.write(i);
</SCRIPT>
</BODY>
But in output I still have 6. How to pass value by reference?
On Javascript pass by reference does not exist. You can use an object to pass and it works like passing by reference.
eg :
var atl = new ActiveXObject("ATL.Object.1");
var i = { value: 6};
//if ActiveXObject does not work with your Object, than you need to make an adapter or store the value back to i
atl.test(i);
document.write(i.value);
I need to dynamically assign the name of a function to an element of an associative array. This is my attempt which does not work. The problem I am asking for help with is here where I try to call the function: cr['cmd1'](x);
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var cr =[];
var x = 5;
cr['cmd1'] ='foo';
var msg = cr['cmd1'](x);
alert(msg);
function foo(y){
return y;
}
</script>
</head>
<body>
</body>
</html>
Edit: I being passed a string here cr['cmd1'] ='foo'; that I cannot control. That is why I have to work with a string as a starting point from an external application.
Access the functions using this syntax window[function_name]('para1');
Your usage will be something like this
var msg = window[cr['cmd1']](x);
If you want to store it as a function, pass the function directly. Otherwise, if you just want to store it as a string, then you can use the quotes.
Change:
cr['cmd1'] ='foo';
To:
cr['cmd1'] = foo;
I would use window[] and make sure its a function before trying to execute it since you don't have control over what is passed.
var f = window[cr['cmd1']];
if(typeof f==='function') {
f(x);
}
What you are doing there is assigning a function to an array. A more common pattern that you are probably trying to do is to call a function on an object with the array notation.
<script type="text/javascript">
var cr = {};
cr.cmd1 = function foo(y){
return y;
};
var x = 5;
var msg = cr['cmd1'](x);
alert(msg);
</script>
This code results in an alert box that contains the number 5.