skip to Main Content

i want to access value of the two input to make calculation immediately they put in a value

<script>
//i want to access value of the two input to make calculation immediately they put in a value
const heightInputEl = document.querySelector('.height-input');
const weightInputEl = document.querySelector('.weight-input');
  heightInputEl.addEventListener('input', function (e) {
  const height = Number(e.target.value);
  const mtrsqr = Math.abs(Math.pow(height / 100, 2));
});

weightInputEl.addEventListener('input', function (e) {
  const weight = Number(e.target.value);
});

</script>


2

Answers


  1. var mtrsqr
    var weight
    
    const heightInputEl = document.querySelector('.height-input');
    const weightInputEl = document.querySelector('.weight-input');
    
    heightInputEl.addEventListener('input', () => {
      let height = Number(heightInputEl.value);
      mtrsqr = Math.abs(Math.pow(height / 100, 2));
    });
    
    weightInputEl.addEventListener('input', () => {
      weight = Number(weightInputEl.value);
    });
    

    By defining mtrsqr and weight outisde the event, we can access them anywhere

    Login or Signup to reply.
  2. Your code is probably not running because it ran even before the said html elements are loaded. Try setTimeout and it should work perfectly as demonstrated in this example using your code – https://jsfiddle.net/hiyer/sL18nqe7/36/

    <html>
    
    <script>
      //i want to access value of the two input to make calculation immediately they put in a value
     setTimeout( function (){
            const heightInputEl = document.querySelector('.height-input');
        const weightInputEl = document.querySelector('.weight-input');
        heightInputEl.addEventListener('input', function (e) {
        const height = Number(e.target.value);
        const mtrsqr = Math.abs(Math.pow(height / 100, 2));
        const mtrsqrEl = document.querySelector('#mtrsqr');
        mtrsqrEl.textContent=""+mtrsqr;
        
          });
    
       weightInputEl.addEventListener('change', function (e) {
        const weight = Number(e.target.value);
        const weightEL = document.querySelector('#weight');
            weightEL.textContent=weight;   
      });
    
    },100);
    
    </script>
    <body>
          Height:<input class="height-input" value="10"/ >
          <br/>
          Weight:<input class="weight-input" value="10">
          <br/>
          Mtrsqr:<label id="mtrsqr"></label>
          <br/>
          Weight:<label id="weight"></label>
          <br/>
    </body>
    
    
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search