I have encountered an issue with storing text in an array for easy retrieval using a value. I want to use template literals within the strings so that they can change based on user input (for example, displaying their name). I have successfully implemented this when including the string directly in the function, as shown below:
textbox.textContent = `what does ${nameTemp} do?`;
This code works perfectly and updates the displayed text according to the user input. However, the following code does not work as expected. It always displays "tim" as the name (default value for "nameTemp"):
textbox.textContent2 = Title[1];
In the provided code snippet, you can see that the first line within the saveName() function, which includes the full string with the template literal, performs correctly. However, the second line, where the string is retrieved from the array, does not update accordingly. Instead, it continues to display 'tim'. What am I missing here? How can I effectively store strings in an array with variable elements? Any suggestions would be greatly appreciated.
var nameTemp = `tim`;
let Title = [];
Title[0] = "What are you called?";
Title[1] = `what does ${nameTemp} do?`;
const input = document.createElement('input');
input.type = "text";
input.id ="nameText";
input.className +='inputStyle';
function addNameInput()
{
container.appendChild(input);
}
function saveName()
{
if (nameText.value !== null)
{
nameTemp = nameText.value;
textbox.textContent = `what does ${nameTemp} do?`; //This works, it displays the inputted name
textbox.textContent2 = Title[1]; // This will always display 'tim'
nameText.parentNode.removeChild(nameText);
incrementState();
}
}