Home > Mobile >  Null value of javascript variable after initialization
Null value of javascript variable after initialization

Time:10-12

I have this html

<lu id="balancingSel" >
   <li><a href="bal.html"> "VALUE1" </a></li>
   <li><a href="bal.html"> "VALUE2" </a></li>
   <li><a href="bal.html"> "VALUE3" </a></li>
   <li><a href="bal.html"> "VALUE4" </a></li>
</lu> 

I want to get the value when on of those list elements is clicked and pass it to another function as you can see below.

Currently i am trying this in my bal.html

<script>
var projectType;

$(function () {
   
    //Initialize project name
    var ul = document.getElementById('balancingSel'); //Parent
    ul.addEventListener('click', function (e) {
        if (e.target.tagName === 'A')
            projectType = e.target.innerText;
    });

    //Load data
    balancingTableLoad($("#balancingFileSelect").val(), projectType);
    fillInputFieldData($("#balancingFileSelect").val(), projectType);
    });
</script>

The issue is that although the value is set to variable projectType when the two other functions are called with that variable as parameter it is undefined.

I tried moving the variable declaration inside the function but that didn't solve the problem.

CodePudding user response:

Your code call the two function even before you click anything, the reason being addEventListener, runs after clicking and those two function execute as soon as they are defined.

 ul.addEventListener('click', function (e) {
        if (e.target.tagName === 'A')
            projectType = e.target.innerText;
     // }); oringally the function addEventListener ends here

    //Load data
    balancingTableLoad($("#balancingFileSelect").val(), projectType);
    fillInputFieldData($("#balancingFileSelect").val(), projectType);
    }); // addEventListener should end here 

CodePudding user response:

You should move the function calls inside the if block, otherwise projectType could be not set:

function balancingTableLoad(val, type) {
  alert(type);
}

function fillInputFieldData(val, type) {
  alert(type);
}

$(function() {

  //Initialize project name
  var ul = document.getElementById('balancingSel'); //Parent
  ul.addEventListener('click', function(e) {
    if (e.target.tagName === 'A') {
      projectType = e.target.innerText;
      //Load data
      balancingTableLoad($("#balancingFileSelect").val(), projectType);
      fillInputFieldData($("#balancingFileSelect").val(), projectType);
    }
  });
});
<ul id="balancingSel" >
   <li><a href="bal.html"> "VALUE1" </a></li>
   <li><a href="bal.html"> "VALUE2" </a></li>
   <li><a href="bal.html"> "VALUE3" </a></li>
   <li><a href="bal.html"> "VALUE4" </a></li>
</ul> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  • Related