Skip to content
Advertisement

number input events in javascript

The listelements are hidden by default, I’d like to select a number from the ‘postnr’ number input then show the listelements. I’m not sure what event I should be using with DOM. I figured I have to somehow loop through the list then run it same number of times as the input. Any advice?

let blogNr = document.getElementById("postnr");
var scene  = document.getElementById("blogposts");

blogNr.oncontextmenu {
  console.log("you changed the form");
}
ul {
  font-size : 20px;
  padding   : 10%;
  display   : none;
}
<input type="number" id="postnr" name="postnr" min="0" max="5">

<ul id="blogposts">
  <li>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Beatae fugit ut quod reiciendis asperiores animi vitae incidunt aspernatur ullam autem.</li>
  <li>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Beatae fugit ut quod reiciendis asperiores animi vitae incidunt aspernatur ullam autem.</li>
  <li>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Beatae fugit ut quod reiciendis asperiores animi vitae incidunt aspernatur ullam autem.</li>
</ul>

Advertisement

Answer

For your reference, here is a list of events – https://www.w3schools.com/tags/ref_eventattributes.asp

Not sure what you are asking exactly, so here are some possible solutions:

  1. You want the <ul> element to show when <input> has a valid value:
let blogNr = document.getElementById("postnr");
let scene  = document.getElementById("blogposts");

blogNr.addEventListener(`change`, (event) => {
  const inputHasValue = !isNaN(event.target.value) && !!event.target.value;
  const useDisplayStyle = inputHasValue ? `block` : `none`;
  scene.style.display = useDisplayStyle;
});
  1. You want the <li> element whose index matches the number input’s value (for ex. if number is 1, show the first <li>) to show:

in that case, it would not make much sense or there is little benefit in using <ul> this way.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement