How to change h1 text depending on cookie value? [duplicate] - javascript

In the following example, why doesn’t the value property of the input with the ID test update to "second"?
document.getElementById("test").addEventListener("click", () => {
let test = document.getElementById("test").value;
test = "second";
console.log(test); // Logs "second", but input value is not updated.
});
<label>Click on this test input: <input type="text" id="test" value="first"></label>

Because Javascript assigned x as a value and not a reference to the original object.
For example, you could instead:
function setText(x) {
document.getElementById('test').value = x;
}
getText = function() {
return document.getElementById('test').value;
}
And the value you set with setText() will be reflected by getText(), since getText() will also use the reference object's value, and not a copy of the value.
EDIT
As Bryan points out, this would be a copy by reference with a global scope:
var test = document.getElementById('test');
function setText(x) {
test.value = x;
}
getText = function() {
return test.value;
}
http://jsfiddle.net/nLj2A/
The original test variable stores a reference to the element, not a value associated with an attribute of the element.

You are copying the value to a variable. Changing the variable won't change the original, because the variable just contains a copy.
If you store the reference of the element in the variable, you can use that to set the value:
var test = document.getElementById('test');
test.value = "second";

You're assigning the element's value to a variable and then changing the variable. This is not reflected back in the element's value. You need to change the element's value instead.
document.getElementById('test').value = "second";

because document.getElementById('test').value
is a getter where as
document.getElementById('test').value = "second"
is a setter

test = document.getElementById('test').value;
...only gives you a copy of the value at that instant. When you modify test, you need to put that back into input field you'd like to change:
var test_input = document.getElementById('test');
test_input.value = "second";

Setting the local variable test to "second" will do nothing. I assume you want getText to update the DOM. Try this:
getText = function() { document.GetElementById('test').value("second"); }

Point to element instead of value: http://jsbin.com/axufi4/edit

Although javascript ultimately treats everything as an object, I believe only arrays and objects are passed by reference. Strings, ints and floats are passed by value.
Text inputs will always give you a string (even if you restrict input to numbers)

<script type="text/javascript">
getText = function() {
var test = document.getElementById('test').value;
test = "second";
//note: if you insert "alert(test)" it returns "second"
document.getElementById('test').value = test;
}
</script>

You need to do this:
document.getElementById('test').value = "second";
or
var el = dcument.getElementById('test');
el.value = "second";
As for why, I believe it has to do with something about Javascript being a "pass by reference" or "pass by value" language, on which subject there was a very interesting discussion here on SO. (I'm not sure on this point, correct me if I'm wrong).

because it's a string and is passed as value, not as reference. so the content of value is copied to test

Because you're setting the value of test to be the string document.getElementById('test').value.
You aren't linking the two together.
If you are looking to do that, you can use a function:
function test(x) {
document.getElementById('test').value = x;
}
test('foo');
In Python, you can do this. In JavaScript, I don't think so.

Related

Using form values javascript

I'm trying to access form data through a Javascript function when an input is 'changed'.
Currently I use something like this:
<form>
<input type="radio" name="type" name="myValue" onchange="myFunction(this.form)>
</form>
<script>
function myFunction(form) {
var value = form.type.value;
}
</script>
And it works, however instead of writing
var value = form.type.value;
I need to write something like this
var myArray = ["type"];
var value = form.myArray[0].value;
Which is not working. Is this due to how values in arrays are handled?
I have it here on JSFiddle if that is useful.
Thanks
Try
var value = form[myArray[0]].value;
form.myArray[0] is first getting the member myArray from form, and then trying to get the first item in that. Equal to (form.myArray)[0]
form[myArray[0]] explicitly says get the member from form which is of the name of the value inside myArray[0]
You can access properties of object using [] like this:
var value = form["type"].value;
// equivalent to:
var value = form.type.value
In your case this should work:
var myArray = ["type"];
var value = form[myArray[0]].value;
'myArray' is declared as a local variable but it is NOT form's property.
So form.myArray will fail.

Trouble with getting access to an object's property

I'm having a trouble with getting access to an object's property.
Isn't it possible to get access to an object's property like this?
key["heading"]
key in the code above is a variable.
This code below is the code I'm working on right now.
alertHeading.on('blur', function(){
var inputtedVal = $(this).val();
var key = alertMode.val();
chrome.runtime.getBackgroundPage(function(backgroundPage) {
var background = backgroundPage.background;
//(1)This works fine.
background.setStorage(key, {heading:inputtedVal});
console.log(background.getStorage(key));// Object {heading: "aaa"}
//(2)This doesn't work.
var alertObject = background.getStorage(key["heading"]);
console.log(alertObject);// null. I'm expecting to get "aaa".
});
})
I think I'm making a very simple mistake which comes from my lack of javascript knowledge.
Please help me out to solve this problem.
Your key isn't an object, it's a string. It is the return from background.getStorage(key) that is an object, so you can do this:
var alertObject = background.getStorage(key)["heading"]; // note () and [] placement
// OR, in two steps:
var alertObject = background.getStorage(key);
var heading = alertObject["heading"];
EDIT:
"I haven't understood why it's not an object but a string yet"
Your key variable is set to the return from jQuery's .val() method:
var key = alertMode.val();
...which returns a string that is the value of the form element that it is called on. Add in a console.log(key) and you'll see.

How to store a div ID value globally

I am creating an application that uses the same number pad to fill out two separate text style form values using javascript.
I found out how to gather a div ID for use inside of a function (for say toggling the hide value), but I need to save this value somehow so that I can know which field to put the numbers into when they come in.
I tried using a global variable for this, but it does not seem to work as the ID does not seem to be recorded as a String value.
The code that I am using does toggle the show/hide attribute, but if I use an alert box to pop what the variable I am using as storage is it reads [object HTMLDivElement]
My script looks like this (bear in mind that I am a noob to javascript).
<script type="text/javascript">
<!--
keypad.display="none";
//Classes for the numberpad on the text fields.
var padName = ""; //Storage for the name of the current pad.
function numPad(field) {
var pad = document.getElementById("keypad"); //manipulating pad.
var ref = document.getElementById(field);//gather the field info.
if (pad.style.display == "block") { //Open or close?
pad.style.display = "none"; //Blank out.
padName = "";
}
else {
pad.style.display = "block";//Set to refer to correct field.
padname = ref;
alert (ref);
}
}
function click(id) {
var key = document.getElementById(id);
var total = padName.value();
if (key == "Backspace") total.slice(0, -1);
else if (key == "Enter") numPad("blanck");
else total += key;
padName.value = total;
}
-->
</script>
// to get the ID by direct property access of the DOM element
var ref = document.getElementById(field).id;
and then ref stores the ID value.
I would suggest:
// create an object to store app-wide settings
// access properties like this: appSettings.propertyName
var appSettings = { padName: "" };
...
var ref = document.getElementById(field).id;
appSettings.padName = ref;
to avoid polluting the global namespace.
To get/set the value of the pad, you'll need to do this:
// to get
var total = document.getElementById(appSettings.padName).value;
// to set
document.getElementById(appSettings.padName).value = "something";
You should read up on DOM objects and properties.
For starters, ref is assigned a reference to a DOM element. You are then assigning this reference to padName, hence the [object HTMLDivElement] alert.
If you just want the ID stored in padName, use
padName = field;
Also, you're mixing cases of padName. You have both padName and padname.
Further, as mentioned in the comments, use the console for debugging. It's much more comprehensive than an alert.
I can't tell what's happening in your click function. You seem to be expecting padName to be an object of some kind however where the value() method and value property comes from is anyone's guess (FYI only form elements have value properties).

If I set `let x = document.getElementById("inputText").value` and update `x`, why doesn’t the value update?

In the following example, why doesn’t the value property of the input with the ID test update to "second"?
document.getElementById("test").addEventListener("click", () => {
let test = document.getElementById("test").value;
test = "second";
console.log(test); // Logs "second", but input value is not updated.
});
<label>Click on this test input: <input type="text" id="test" value="first"></label>
Because Javascript assigned x as a value and not a reference to the original object.
For example, you could instead:
function setText(x) {
document.getElementById('test').value = x;
}
getText = function() {
return document.getElementById('test').value;
}
And the value you set with setText() will be reflected by getText(), since getText() will also use the reference object's value, and not a copy of the value.
EDIT
As Bryan points out, this would be a copy by reference with a global scope:
var test = document.getElementById('test');
function setText(x) {
test.value = x;
}
getText = function() {
return test.value;
}
http://jsfiddle.net/nLj2A/
The original test variable stores a reference to the element, not a value associated with an attribute of the element.
You are copying the value to a variable. Changing the variable won't change the original, because the variable just contains a copy.
If you store the reference of the element in the variable, you can use that to set the value:
var test = document.getElementById('test');
test.value = "second";
You're assigning the element's value to a variable and then changing the variable. This is not reflected back in the element's value. You need to change the element's value instead.
document.getElementById('test').value = "second";
because document.getElementById('test').value
is a getter where as
document.getElementById('test').value = "second"
is a setter
test = document.getElementById('test').value;
...only gives you a copy of the value at that instant. When you modify test, you need to put that back into input field you'd like to change:
var test_input = document.getElementById('test');
test_input.value = "second";
Setting the local variable test to "second" will do nothing. I assume you want getText to update the DOM. Try this:
getText = function() { document.GetElementById('test').value("second"); }
Point to element instead of value: http://jsbin.com/axufi4/edit
Although javascript ultimately treats everything as an object, I believe only arrays and objects are passed by reference. Strings, ints and floats are passed by value.
Text inputs will always give you a string (even if you restrict input to numbers)
<script type="text/javascript">
getText = function() {
var test = document.getElementById('test').value;
test = "second";
//note: if you insert "alert(test)" it returns "second"
document.getElementById('test').value = test;
}
</script>
You need to do this:
document.getElementById('test').value = "second";
or
var el = dcument.getElementById('test');
el.value = "second";
As for why, I believe it has to do with something about Javascript being a "pass by reference" or "pass by value" language, on which subject there was a very interesting discussion here on SO. (I'm not sure on this point, correct me if I'm wrong).
because it's a string and is passed as value, not as reference. so the content of value is copied to test
Because you're setting the value of test to be the string document.getElementById('test').value.
You aren't linking the two together.
If you are looking to do that, you can use a function:
function test(x) {
document.getElementById('test').value = x;
}
test('foo');
In Python, you can do this. In JavaScript, I don't think so.

JavaScript: Convert string to value of predefined variable

I have a JavaScript object that looks like the following:
venue = function(map, dataSet) {
// set some constants
this.VENUE_ID = 0;
this.VENUE_NAME = 1;
this.VENUE_CITY = 2;
this.filterBy = function(field, value) {
...
var filterValue = 'parent.VENUE_' + field;
}
}
Now, the problem is that I need the value of filterValue to contain the value of the constant on the parent object. Currently I have tried using the method shown above and then referencing the filterValue when trying to access the array item, but this simply returns undefined.
How do I convert the filterValue variable into the value of the constant it represents?
This has nothing to do with the variable scope.
var filterValue = this['VENUE_' + field];
would do.
JavaScript has no concept of 'parent'. And I think you're confusing scope and context. If that method was written as var filterBy() you'd have to access it in a different 'scope'. But by using 'this' you kept in in the same object as it was written. So everything you wrote is in 'this' context.
Try this:
var filterValue = this['VENUE_' + field];

Categories

Resources