Home > front end >  How to pass variable from one function to another Javascript?
How to pass variable from one function to another Javascript?

Time:08-24

I have two functions one which defines path based on if else conditions and I want to use that path in another function to plot a graph. catchit function is being called using onclick in HTML. This is what I have done but in console it is giving the value of path1 undefined. Any idea how I can make it work?

allpredicted.js

var path;         
 function catchit(no){    
    console.log(no)
    if (no ==1) {
        path="/static/data/submission1.csv"
      } else {
        path="/static/data/submission2.csv"
      
      } 
    parseData()
    }

 function parseData(createGraph) {
    var path1=path;
    console.log(path1);
    Papa.parse(path1,{
      download: true,
      complete: function(results) {
        createGraph(results.data);
        
      }
    });
  } 

cotton.html

<div  >
  
  
  <button  id="1" button-id="1" onclick="catchit(1)" ><a  href={% url 'reports' %}>Formget Online Form Builder Create Online </a></button>
       <div >
      </div>
     <button   id="2" value="2" button-id="2" onclick="catchit(2)" ><a  href={% url 'reports' %}>Formget Online Form Builder Create Online </a></button>
      <div >
      </div>
     <button   button-id="3" onclick="catchit(3)" >Formget Online Form Builder Create Online Forms</button>
    
      
     <script src="{% static 'javascripts/allpredicted.js' %}"  ></script>
     
     
    
    
    </div>

CodePudding user response:

Just add another argument to parseData.

var path;

function catchit(no) {
    console.log(no)
    if (no == 1) {
        path = "/static/data/submission1.csv"
    } else {
        path = "/static/data/submission2.csv"

    }
    parseData(createGraph, path);
}

function parseData(createGraph, path) {
    var path1 = path;
    console.log(path1);
    Papa.parse(path1, {
        download: true,
        complete: function(results) {
            createGraph(results.data);

        }
    });
}

catchit(no);

CodePudding user response:

var path
function catchit(no) {
    path = []
    if (no == 1) {
        path.push("/static/data/submission1.csv")
    } else {
        path.push("/static/data/submission2.csv")
    }
    parseData()
}

function parseData(createGraph) {
    var path1 = path.join("");
    console.log(path1);
}

catchit(1)
catchit(2)

  • Related