So I am trying to have a program where a variables name is determined by user input, like:
<html>
<script>
var name = prompt("User input")
var hold = prompt("More stuff")
var (Test + (name)) = (hold)
</script>
</html>
But this doesn't work. What can I do?
You can't name variables by a string. You can name properties on an object however.
var name = prompt("User input")
var hold = prompt("More stuff")
var obj = {};
obj['Test' + name] = (hold)
Related
Hello everybody I am relatively new to coding. I have a local storage project in object oriented javascript for reservation data and to display them in a reservation summary.I am currently blocked, I manage to recover the various values with "getItem", but when I want to display them on my html it displays "object HTMLSpanElement".
the only solution I found is to add ".textcontent" at the end of my variables but it doesn't work.
this is my code
class information{
constructor(){
this.StationName = document.getElementById("StationName");
this.name = document.getElementById("name");
this.firstname = document.getElementById("firstname");
this.adresse = document.getElementById("adresse");
this.PlacesTotal = document.getElementById("PlacesTotal");
this.nbrVeloDispo = document.getElementById("nbrVeloDispo");
};
initstorage(){
var StationName = document.getElementById("StationName").textContent;
var name = document.getElementById("name").value;
var firstname = document.getElementById("firstname").value
var adresse = document.getElementById("adresse").textContent;
var PlacesTotal = document.getElementById("PlacesTotal").textContent;
var nbrVeloDispo = document.getElementById("nbrVeloDispo").textContent;
};
initreservation(){
var StationName = localStorage.getItem("StationName");
var name = localStorage.getItem("name");
var firstname = localStorage.getItem("firstname");
var adresse = localStorage.getItem("adresse");
var PlacesTotal = localStorage.getItem("PlacesTotal");
var nbrVeloDispo = localStorage.getItem("nbrVeloDispo");
};
reserver(){
document.getElementById("signature").style.display = "block";
document.getElementById("panneaureservation").style.display = "none";
};
};
document.getElementById("reservation1").innerHTML = StationName;
const stockage = new information();
document.getElementById("reserve").onclick = function() { stockage.initstorage(); stockage.initreservation(); stockage.reserver(); }
Thank you for taking your time to help me.
When you call localStorage.setItem() you are attempting to store a reference to the DOM element itself instead of the content of that element. Since localStorage only stores strings, the object implicitly gets its .toString() method called on it and a string representation of the object's type and element name is what gets stored.
Here's an example of what's happening (described above):
console.log(document.querySelector("div").toString());
<div>My div element</div>
Once that happens, you can't extract the reference later because all you have is the string name of the object.
You didn't show that code, but that's what needs to be updated. It should store the string value that you will want to get later. Something like this:
localStorage.setItem("StationName", document.getElementById("StationName").textContent);
localStorage.setItem("name", document.getElementById("name").value);
localStorage.setItem("firstname", document.getElementById("firstname").value);
localStorage.setItem("adresse", document.getElementById("adresse").textContent);
localStorage.setItem("PlacesTotal", document.getElementById("PlacesTotal").textContent);
localStorage.setItem("nbrVeloDispo", document.getElementById("nbrVeloDispo").textContent);
Where you set the .textContent of non-form field DOM elements and the .value of form field DOM elements. And, of course, you don't want this code to run against form field data until the form has been completed.
I have 2 strings. One represents the variable name and the other the value.
This might explains it better:
var data = ['varName', 'content'];
var obj = { data[1]: data[2] }
The other post I've found yet only refer to an objects name.
You can set it like this:
var data = ['varName', 'content'];
var obj = {};
obj[data[0]] = data[1];
I am trying to add find a property of an object using a variable but it is not working. When I write the object name iso of the variable, it is working, although the variable and the object name are exactly the same..
function calCulate(nrs){
const product = {DE2599:{name:"tet", bar:2.5, price: 3.5}};
var nr = document.getElementById(nrs).value;
var sku = ("prod" + nr);
var qty = ("qty" + nr);
var pric = ("price"+nr);
var pal = ("pallet"+nr);
var ctry = document.getElementById('country').value;
var x = document.getElementById(qty).value;
var test = document.getElementById(prod).value;
var tests = test.toString(); // way of getting the result
var testr = tests.indexOf(" "); // way of getting the result
var testt = tests.slice(0,testr); // way of getting the result
var uniqueID = ctry+testt; // this value returns DE2599
var mywindow = window.open('','PRINT','height=800,width=800');
var ter = product.uniqueID; // I use uniqueID because it can vary
var tar = ter.price;
mywindow.document.write(tar); // this is not showing any result; but if I change the uniqueID with the actualy key, ie DE2599, it is working correctly
uniqueId is not a property of product so your ter will be storing undefined (and you should be getting an error for tar).
When you need to use the value of a variable to access the property of an object, you need to use bracket notation.
const product = {DE2599:{name:"tet", bar:2.5, price: 3.5}};
let uniqueId = 'DE2599';
console.log('with dot notation');
console.log(product.uniqueId);
console.log('with bracket notation');
console.log(product[uniqueId]);
I am creating a script to populate an email template with random variables, using the replace() method.
Unfortunately, I am struggling to find a way of inserting a gender pronoun, based on the gender of a random name chosen from a string. Is there a way to do this using the excerpts of the scripts below (or am I missing something incredibly obvious)?
HTML
<p id="lineTwo">firstName told genderPronounOne friends...</p>
JavaScript
//Random Name
var maleNames = ['Tom', 'Tony'];
var femaleNames = ['Tina', 'Tracy'];
var maleRandom = maleNames[Math.round(Math.random()*(maleNames.length-1))]+'\n';
var femaleRandom = femaleNames[Math.round(Math.random()*(femaleNames.length-1))]+'\n';
var nameGender = [maleRandom, femaleRandom
var name = nameGender[Math.round(Math.random()*(nameGender.length-1))]+'\n';
//Determine Gender
var pronounOne;
if(/* this is where I'm struggling */){
pronounOne = 'his';
} else {
pronounOne = 'her';
}
//Replace HTML
var replaceHTML = document.getElementById("lineTwo").innerHTML;
var replaceName = replaceHTML.replace("firstName", name);
var replacePronoun = replaceHTML.replace("genderPronounOne", pronounOne);
document.getElementById("lineTwo").innerHTML = replaceName;
document.getElementById("lineTwo").innerHTML = recplacePronoun;
Can anyone help? Thank you.
Store the 0 or 1 in a variable and use it
var mf = Math.round(Math.random()*(nameGender.length-1))
var name = nameGender[mf]+'\n';
//Determine Gender
var pronounOne = mf ? "her" :'his';
How about you check to see if the name that you selected is in the array of male names?
if (maleNames.indexOf(name) > -1) {
pronounOne = 'his';
} else {
pronounOne = 'her';
}
var cur_storage_unit = $('#storage_unit').val();
$('.size_unit').change(function() {
var id = $(this).attr('id');
//This is how I want it to work, but not sure how
'cur_' + id = $(this).val();
});
The user 'changes' a of class 'size_unit' and id of 'storage_unit'. I want to then set the value of 'cur_storage_unit' to the new value of 'storage_unit'. In italics is how I want it to work, but I'm not sure the syntax of how to get it to work. Thanks!
You're probably better off using an Object, and storing it in there.
var cur_storage_unit = $('#storage_unit').val();
var values = {}; // storage for multiple values
$('.size_unit').change(function() {
var id = this.id;
values['cur_' + id] = this.value; // store this value in the "values" object
});
// Accessible via values object
alert( values["cur_theid"] );
you can create a new property on an object using a string as a key
var myObj = {};
myObj['cur_'+id] = $(this).val();
so in your case you would want an object with a known name where you can add dynamically named properties.
If it's global you can do window['cur_'+id];