the pair of elements refuse to change based on the user's input

When I input a value for typeColor, I expect the background color of the box to change. Similarly, when I input a value for typeName, I want the text on the box to update. However, neither of these actions are working as intended. The color doesn't change and the name disappears altogether. I've experimented with different solutions but haven't found one that works.

box = document.getElementById("box");
typeColor = document.getElementById("typeColor").value;
typeName = document.getElementById("typeName").value;
boxName = document.getElementById("boxName");

function changeBoxColor() {
  box.style.backgroundColor = typeColor;
}

function changeBoxName() {
  boxName.innerText = typeName;
}
body {
  margin: 0px;
}

#box {
  width: 100px;
  height: 100px;
  background-color: grey;
  margin-left: 100px;
  margin-top: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
}
<head>
  <title>test</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <input id="typeColor" placeholder="Enter a color...">
  <button onclick="changeBoxColor()">Change Box Color</button>
  <input id="typeName" placeholder="Enter a name...">
  <button onclick="changeBoxName()">Change Box Name</button>

  <div id="box">
    <center>
      <p id="boxName">Box</p>
    </center>
  </div>
  <script src="script.js"></script>
</body>

Answer №1

If you want the input values to update, make sure to place them inside the function rather than loading them with the file.

let box = document.getElementById("box");
let boxName = document.getElementById("boxName");

function changeBoxColor() {
  let typeColor = document.getElementById("typeColor").value;
  box.style.backgroundColor = typeColor;
}

function changeBoxName() {
  let typeName = document.getElementById("typeName").value;
  boxName.innerText = typeName;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can you inform TypeScript about a file that will be included using a script tag?

I am currently utilizing TypeScript for my front-end JavaScript development, and I have a situation where I am loading two scripts from my index.html file as shown below: <script src="replacements.js"></script> <script src="socket.js">&l ...

Storing user input data after submitting a form in ExpressJS

Seeking advice for my Express.js application on how to store form data (specifically from a text area) following a post request, while avoiding the use of AJAX. I hope this question is clear. Appreciate any guidance in advance. ...

Encountered a 'node:internal/modules/cjs/loader:1146' error while setting up a React application

Encountering these console errors node:internal/modules/cjs/loader:1146 throw err; ^ Error: Module '../../package.json' not found Require stack: - C:\Users\adity\AppData\Roaming\npm\node_modules\npm\li ...

Retrieve the information enclosed by comments using an HTML DOM parser

Looking to extract the plain text content between two comments, but struggling to find a solution without relying on specific HTML tags in the structure. Parse between comments in Simple HTML Dom Wondering if it's achievable with HTML Dom Parser? ...

What is the method to update a div containing the video title when a user clicks on a related video?

How can I make a div update with the title of the currently playing video when a user clicks on another video? I am having trouble finding an event in the API that lets me know when the video source has changed. Is there a specific event I should be listen ...

Position a div next to a table and include scrollbars

My challenge is to create a responsive layout with a table and a side div, as shown in the image below. I attempted to use CSS float properties for the table and side div, but it did not provide the responsiveness I needed. I then tried implementing Bootst ...

The most effective method for transferring variables between a child and parent function in JavaScript

For instance function getOutput(field) { $.ajaxSetup ({cache: false, async: false}); $.get("api.php?field="+field, function(data) { output = data; }); return output; }; An issue lies in the fact that output becomes a global variab ...

The CSS property "margin: 0 auto" is failing to align content in the center

It's so frustrating... can someone please explain why the center column won't align between the left and right columns? I've been trying to use margin: 0 auto; on the center column but it's not working. $(document).ready(function ...

Table lines that are indented

I am currently in the process of transforming a standard HTML table into an indented version like this: Is there a way to hide the initial part of the border so that it aligns with the start of the text, even if I can't do it directly in HTML? ...

Connecting two fields with a line on click in AngularJS

In the top section, there are 10 fields and in the bottom section, there are another 10 fields. I want to be able to connect two fields with a line when they are clicked (one from the top section and one from the bottom section). This connection should app ...

React Router Blank Page Conundrum

In a new project, I'm experiencing an issue where the content is not loading in despite using a similar React-Route setup that worked in a previous project. When I create a nav link in the root directory, it changes the path but the screen remains whi ...

I'm encountering an issue while trying to install npx create-react-app. I've attempted to use npm globally as well, but unfortunately, neither option is

While trying to install my React app using npx create-react-app my-app, I encountered the following errors: PS C:\Users\NAEEM UR REHMAN\Desktop\react_app> npx create-react-app my-app npm ERR! code ERR_INVALID_URL npm ERR! Invalid U ...

Tips for managing Ajax JSON response in a PhoneGap application

Although there are a few posts on this topic, I am struggling to piece together the necessary components to make it work. I am in the process of converting a web application into an app using phonegap and I am attempting to create a search form that retri ...

Toggle button in VueJS that dynamically shows/hides based on the state of other buttons

In my table, I have included options for the days of the week such as Everyday, Weekdays, and Weekend. Each row contains 2 select items to choose start and end times for updates. Additionally, there is a toggle button at the end of each row that enables or ...

Customized queries based on conditional routes - expressjs

Can we customize queries based on optional routes? app.get('/:category/:item?', function (req, res) { var category = req.params.category; var item = req.params.item; var sqlQuery = 'SELECT * FROM items WHERE category = ? AND item = ?&a ...

interactive switch using font awesome icons and jquery

Initially, I assumed this would be an easy task, but I've encountered some difficulties in making it function smoothly. Although I am able to toggle once using .show and .hide, I am unable to toggle back. Any assistance would be greatly appreciated. ...

testing express router with several different handlers

I have been testing my guard middleware and everything appears to be functioning correctly, but my expect statement is failing. /// auth.test.js const request = require('supertest'); const express = require('express'); const app = req ...

HTML embed social media feeds

While I understand that using iframes may not always be the preferred method, in my case it simplifies things. Website A contains links to different sections on the same site using <a name=.... Website B has an iframe that includes website A. Everything ...

What is the proper way to initialize a function that interacts with the redux state?

Imagine a scenario where I have a function that retrieves a filepath from the state based on the filename provided as an input parameter. If the filepath does not exist in the state, it then fetches the filepath from a server URL. const getFilepath = (stat ...

Using an Array of Deferreds with $.when() does not trigger the done action

I have a challenge with implementing a dynamic set of deferred functions in an array along with $.when(). These functions are responsible for fetching data from the server and rendering it on the DOM. Following the completion of these operations, several s ...