Modify the value during the oninput event in TypeScript

I am trying to dynamically change a span element based on the input value when the event 'input' is triggered.

Below is my HTML code:

<div class="slidecontainer">
    <input type="range" min="1" max="1000" value="50" class="slider" id="myRange" step="3" class="myRange">
    <p>Value: <span id="demo"></span></p>
    <p>Time saved: <span id="time"></span></p>
</div>

This is my TypeScript file:

var slider = document.getElementById("myRange") as HTMLInputElement;
var output = document.getElementById("demo");
output.innerHTML = slider.value;

var convertSlider = parseInt(slider.value); 
var timeSaved = Math.round(convertSlider * 4* (1 - Math.min(convertSlider, 200) * 40 / 10000)).toString();
var timeSavedOutput = document.getElementById("time");
timeSavedOutput.innerHTML = timeSaved; 

slider.oninput = e => {
  output.innerHTML = ((<HTMLTextAreaElement>e.target).value);
  timeSavedOutput.innerHTML = timeSaved;
};

Even though I have successfully displayed the value in my #time span, it does not update when I adjust the slider. How can I capture the event to ensure that the value in my #time span also updates accordingly?

Answer №1

It seems like there might be some confusion in the code you provided:

output.innerHTML = ((<HTMLTextAreaElement>e.target).value);
. To achieve the desired result, the assignment should actually be to the value of the slider.

var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
var gainTimeOutput = document.getElementById("time");

slider.oninput = e => {
  output.innerHTML = slider.value;
  
  var convertSlider = parseInt(slider.value); 
  var gainTime = Math.round(convertSlider * 4* (1 - Math.min(convertSlider, 200) * 40 / 10000)).toString();
  gainTimeOutput.innerHTML = gainTime; 
};
<div class="slidecontainer">
    <input type="range" min="1" max="1000" value="50" class="slider myRange" id="myRange" step="3">
    <p>Value: <span id="demo"></span></p>
    <p>Gain de temps: <span id="time"></span></p>
</div>

Answer №2

To ensure that your input can modify its value, consider adding the onChange attribute.

For example:

<input type="range" min="1" max="1000" value="50" onChange="updateInput()" class="slider" id="myRange" step="3" class="myRange" />

Don't forget to encapsulate your code in a function within your script:

function updateInput() {
   console.log("hello")
   // add your custom logic here
}

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

The command "npm run build" is failing and encountering errors within the webpack project

Today, when I ran npm run build in the terminal, my project stopped running and displayed 90 errors and 13 warnings. It was working fine yesterday, so I'm not sure what the issue could be. The only change I made was to a line of JavaScript code that i ...

Guide to integrating Firebase token authentication with a web API2 controller

In order to pass a Firebase authentication token to a web API controller, I am following steps outlined in this StackOverflow post: stackoverflowpost The bearer token is included in the $http request headers. https://i.sstatic.net/GTJz0.png Despite addr ...

Transferring data from JavaScript to ASP.NET (via AJAX)

I'm trying to figure out how to pass variables from JavaScript to a textbox. I have a variable in JavaScript but I am unsure how to transfer it to the textbox. I have heard that using AJAX makes it easy, but I don't know how to implement it. I th ...

Leveraging external JSON data in a Jade template with Node.js

Is there a way to successfully pass a Json Object from XMLHttpRequest to my jade file? I am currently experiencing a blank page display and a 500 internal error being sent by the server for the get method. var express = require('express'); var r ...

Can a single file in NextJS 13 contain both client and server components?

I have a component in one of my page.tsx files in my NextJS 13 app that can be almost fully rendered on the server. The only client interactivity required is a button that calls useRouter.pop() when clicked. It seems like I have to create a new file with ...

adjusting the scrollbar to be positioned at the top when using Material UI stepper component

While using the material ui stepper, I encountered an issue where the scroll bar remains static and hidden behind the step number header when I click on the "save and continue" button. I expect that upon clicking the button, the scroll bar should automatic ...

Prevent the Swiper slider from autoplaying while a video is being played, and automatically move to the next slide once the video is paused or

<div class="swiper mySwiper"> <div class="swiper-wrapper"> <div class="swiper-slide"> <video-js id="6304418462001" class="overlayVideo" data-account= ...

The Access-Control-Allow-Origin error is preventing the Angularjs post request from going through

I am encountering an issue with my index.html file that is sending a post request to localhost:3000/SetUser. The error I keep receiving states XMLHttpRequest cannot load https://localhost:3000/SetUser. No 'Access-Control-Allow-Origin' header is p ...

Implementing Service Communication

I created an Angular Application using the Visual Studio Template. The structure of the application is as follows: /Clientapp ./app/app.module.shared.ts ./app/app.module.client.ts ./app/app.module.server.ts ./components/* ./services/person-data.service. ...

The transfer of information through HTTP

I have been exploring the inner workings of HTTP servers and clients to better understand how data is transmitted. Despite reading numerous articles on the topic, I still have some lingering questions that remain unanswered. I would like to walk through th ...

Is it possible to generate a Token in Nexus for private packages without using the UI interface?

We have implemented Sonatype Nexus Repository ManagerOSS 3.29.0-02 and are currently facing an issue in generating a TOKEN that can be used with .npmrc following this specific structure: registry=http://NEXUS-IP:8081/repository/GROUP-NAME http://NEXUS-IP:8 ...

Accessing the current position of skeleton bones in Three.js while an animation is playing

I currently have a Three.js project with an animated scene and I am trying to obtain the positions of skeleton bones at various points in time. If I visit, for instance, and inspect the Three.js scene: const modelViewer = document.querySelector("m ...

Navigating a jQuery collection using iteration

My goal is to loop through an array and set values to an element in the following manner: <tool>hammer</tool> var tools = ["screwdriver", "wrench", "saw"]; var i; for (i=0; i < tools.length; ++i){ $("tool").delay(300).fadeOut().delay(100). ...

When we modify the prototype of the parent object, where does the __proto__ point to?

Typically, when a new object is created using the "new" keyword, the __proto__ property of the newly created object points to the prototype property of the parent class. This can be verified with the following code: function myfunc(){}; myfunc.prototype.n ...

Error Encountered: Angular 2 ngOnInit Method Being Executed Twice

Encountered an unusual error in Angular 2 while working on two components that share similarities in templates and services. Here is a breakdown of how they function: Component: data: any; constructor(private _service: TheService) {} ngOnInit() { t ...

What is the best way to access nested JSON array data that includes varying key names and content?

In my current project, I am trying to extract data from a JSON array. Here is my approach: Below is the jQuery/JavaScript code I used to generate and retrieve data, particularly focusing on the nodes object which determines different layouts: var getPost ...

D3 mouse interaction differs from touch events, such as clicking -> supported touch event

Searching for examples of using D3 on a mobile device with touch events instead of mouse events has been challenging. I am unable to find clear information on what touch event corresponds to each mouse event, such as click or dblclick. This has hindered my ...

Having trouble with implementing image resizing and cropping in a Node.js environment

Struggling with image processing in node js, this task is crucial for my application. The goal is clear: 1) User uploads an image (multipart formdata sent to the server - successful) 2) Resize the image to a max width of 640px 3) Crop the picture within s ...

Creating a JavaScript function that converts data from JSP to JavaScript using single

I am struggling to pass a string into a JavaScript function successfully. Despite trying multiple approaches, I have not been able to make it work. <a href="javascript:goFac('<%=name%>')"><%=name%></a> The variable "name ...

Want to easily switch between pictures in the Gallery?

I've created a gallery using jQuery, CSS & HTML and now I want to implement next and previous image buttons. I have added the buttons to the page and written functions for them, but I am struggling with the implementation. Here is my code, if anyone h ...