Home > Back-end >  Text input does not change slider value on first attempt
Text input does not change slider value on first attempt

Time:05-24

I am making a password generator with a text input and slider value that are tied together, however when I type in a value the first time it will not update. When I try again it works, as well as working subsequent times. The slider value always updates. I don't know what is wrong with the code to make it perform like this though, still fairly new to JS.

//html

<div >
    <input type="text" id="slider-input" value="" onchange="setSlider(this)">
    <input type="range" min="1" max="64" value="1" id="slider" oninput="myFunction(this)">
</div>

//JS

const sliderInput = document.getElementById("slider-input");
const slider = document.getElementById("slider");

let passLength = "";
function myFunction() {
    slider.oninput = function() {
    sliderInput.value = this.value;
    passLength = this.value;
    }
}

function setSlider() {
    sliderInput.addEventListener("change", function() {
    slider.value = this.value; 
    passLength = this.value;
    })
}

CodePudding user response:

Take a look at the setSlider function. On the first invocation you are adding the event listener. Therefore, it is only after that initial call that we see the intended behavior.

Rather than calling addEventListener on each change, you can remove it all together:

function setSlider({value}) {
  slider.value = value; 
  passLength = value;
}

repl

  • Related