Home > Enterprise >  Making a "range" input type dynamic with an "onchange" event
Making a "range" input type dynamic with an "onchange" event

Time:09-27

I have been trying to attach an onchange event to this snippet of code to make the range input dynamic as it slides, for over 2 days, but nothing seems to be working. It's for an interest rate calculator and I no longer have any idea what to do.

Can someone please show me how to make my slider dynamic? I've attached the relevant snippets of code below.

I've now edited the code for brevity.

function compute() {
  function updateRate(rate) {
    var rateval = document.getElementById("rate").value;
    document.getElementById("rate_val").innerText = rateval;
  }
}
<!DOCTYPE html>
<html>

<head>
  <script src="script.js"></script>
  <link rel="stylesheet" href="style.css">
  <title>Simple Interest Calculator</title>
</head>

<body>
  <div >
    <h1>Simple Interest Calculator</h1>

    <form id="form1">
      <label for="Interest Rate"></label> Interest Rate <input type="range" id="rate" min="1" max="20" step="0.25" default value="10.25">10.25%<span id="rate_val">
      <br/>
      <br/>
  </div>
</body>
</html>

CodePudding user response:

Calling onchange(); on the input in the html. and passing this as a parameter.

Js:setting innertext of span to event.value event is the this i passed from the html..

Your html was also wrong:the text that was suppose to be inside the label was put after it ends.

span was opened but never closed & same text that gonna go inside span was put after it..

Indent your code after a new tag to make a habit of opening & closing tags.Until you get a hold on it. Good Luck...

function updateValue(event) {
 
  document.getElementById("rate_val").innerText = event.value;
}
<div >
  <h1>Simple Interest Calculator</h1>

  <form id="form1">
    <label for="Interest Rate">Interest Rate</label>
    <input onchange=updateValue(this) type="range" id="rate" min="1" max="20" step="0.25" default value="10.25">
    <span id="rate_val">10.25%</span>


  </form>
</div>

CodePudding user response:

The code is pretty self explanatory, i'm just using the input event to update the interest rate.

const rate = document.getElementById("rate");

function updateInterestRate() {
  document.getElementById("rate_val").innerText = rate.value   '%';
}

function initializeSlider() {
  updateInterestRate();
  rate.addEventListener("input", updateInterestRate)
}

initializeSlider();
<div >
  <h1>Simple Interest Calculator</h1>

  <form id="form1">
    <label for="Interest Rate"></label> Interest Rate <input type="range" id="rate" min="1" max="20" step="0.25" default value="10.25">
    <span id="rate_val">10.25%</span>
    <br/>
    <br/>

</div>

  • Related