0

How to pass dynamic variable inside function to another function inside it

i am trying to set dynamic clearing function and i am having issue with this code

var firstName = document.getElementById('firstName');
var lastName = document.getElementById('lastName');
var email = document.getElementById('Email');

    function Clear(Vars) {
        for (i = 0; i < Vars.length; i++) {
           Vars[i].addEventListener("click", Clr, false);
           Vars[i].addEventListener("oninput", Clr, false);
          }
            function Clr(){
               Vars[i].setCustomValidity('');
               Vars[i].style.removeProperty('border');
            }

     };

Clear([email, firstName, lastName]);

trying to find an easy way to pass "Vars[i]" to the second function.

2
  • Your issue is with i, not Vars. Can't you just use this? Commented Jul 23, 2017 at 14:50
  • ohh i see that now , any idea how to pass the "i" to 2nd function without typing for loop again ? also i am trying to avoid "this" for now THANKS Commented Jul 23, 2017 at 14:57

2 Answers 2

1
 function Clr(){
         this.setCustomValidity('');
         this.style.removeProperty('border');
 }

either use this, or use let :

 for (let i = 0; i < Vars.length; i++) {
      function Clr(){
           Vars[i].setCustomValidity('');
           Vars[i].style.removeProperty('border');
        }

       Vars[i].addEventListener("click", Clr, false);
       Vars[i].addEventListener("oninput", Clr, false);
 }
Sign up to request clarification or add additional context in comments.

3 Comments

i am trying to avoid "this" at the moment and the second option Vars came undefined
@RaadAltaie cause you probably forgot the let
i added "function Clear(Vars) { " line , its working now thanks
1

Firstly, are you sure your code work correctly? When for loop is end, i value is Vars.length. So in Clr function, Vars[i] should be undefined. Following code may be helpful for you:

var firstName = document.getElementById('firstName');
var lastName = document.getElementById('lastName');
var email = document.getElementById('Email');

  function Clear(Vars) {
      for (i = 0; i < Vars.length; i++) {
        (function (i) {
          Vars[i].addEventListener("click", Clr, false);
          Vars[i].addEventListener("oninput", Clr, false);
          function Clr(){
             Vars[i].setCustomValidity('');
             Vars[i].style.removeProperty('border');
          }
         })(i);
       }
   };

Clear([email, firstName, lastName]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.