For context, I’m just learning JS. On my web-page, I want to have the option to create new range-inputs that are interactive. I also want to use the values of the ranges for an equation. Right now, I can add the ranges themselves fine, and they work, but the values of each range returns as undefined
.
I found this out while trying this in JavaScript:
document.addEventListener('input', function(event) { if(event.target.matches('.range')) { console.log(event.value); } })
Also, here is the code I did for creating new Range Inputs:
function addSolvr() { solvContain = document.querySelector('.solveContainer') const solvDiv= document.createElement('div'); solvDiv.className="rangeContain" solvContain.appendChild(solvDiv); const solvLabel = document.createElement('input'); solvLabel.classList.add('form-label', 'rangeLabel'); solvDiv.appendChild(solvLabel); const solvAssist = document.createElement('input'); solvAssist.type="number"; solvAssist.className="rangeAssist"; solvAssist.value = 0 solvDiv.appendChild(solvAssist); const solvRange = document.createElement('input'); solvRange.type = "range"; solvRange.className="range"; solvDiv.appendChild(solvRange); } addBtn.addEventListener('click', addSolvr)
Is there a way to get the accurate value from each range? It may be helpful to know that I was able to do this before, but that was with static elements. This time, I’m using appendChild() for creating the range. Thank you!
Advertisement
Answer
You’re getting undefined, because there is no value property in the event.
To access the value of the element, you have to use event.target.value
. That way you’re getting the value of the targeted element. Like so…
document.addEventListener('input', function(event) { if(event.target.matches('.range')) { console.log(event.target.value); } });