0
$(function () {

    var info = JSON.parse($('#userInfo').text());
    var empFirstName = info.EmployeedFirstName;
    var empLastName = info.EmployeedLastName;
    var empFullName = empFirstName + " " + empLastName;
});

I am calling the summary function from a hyper link. I only want to call the summary function when the link is clicked on.

<a onclick="summary();">Summary</a>

function summary(empFullName){
}
CupawnTae
  • 14,192
  • 3
  • 29
  • 60
  • 3
    Scope of `empFullName` isn't available outside of `$(function(){})` since you declared it with `var` inside it – charlietfl May 22 '15 at 22:37

2 Answers2

1

Remove the inline function call from the link and add a click event handler to your link, then call the function and pass your variable to it, when the click handler gets called. Take a look at the snippet and you will get the idea.

$(function () {

  //var info = JSON.parse($('#userInfo').text());
  //var empFirstName = info.EmployeedFirstName;
  //var empLastName = info.EmployeedLastName;
  var empFullName = 'foo' + " " + 'bar';
  
  // added click event handler here
  $('a').on('click', function() {
     summary(empFullName); // call summary with empFullName
  });
  
});

function summary(empFullName){
  console.log(empFullName);
  $('#output').text(empFullName);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#">Summary</a>
<div id="output"></div>
DavidDomain
  • 14,976
  • 4
  • 42
  • 50
0

This will work for you, but you should look into the window object, global variables, and why they may be considered bad.

$(function () {    
    var info = JSON.parse($('#userInfo').text());
    var empFirstName = info.EmployeedFirstName;
    var empLastName = info.EmployeedLastName;
    window.empFullName = empFirstName + " " + empLastName;
});

function summary(empFullName){
    // use empFullName here
}

Then modify your link to pass in the global

<a onclick="summary(empFullName);">Summary</a>

Some related reading: Should I use window.variable or var?

Community
  • 1
  • 1
CupawnTae
  • 14,192
  • 3
  • 29
  • 60