Mason Mason - 5 months ago 10
Javascript Question

jQuery - Passing variable within a function to another function

I have a few different functions that set a variable if the user clicks on a certain button. It then passes that variable on to an AJAX function....except it doesn't pass the variable.

Here is an example:

$('#Button1').on('click', function(e) {
var add1 = 'yes';
e.preventdefault();
})
$('#Button2').on('click', function(e) {
var add1 = 'no';
e.preventdefault();
})
$('#DoneButton').on('click', function(e) {
submitLink = 'submit.php'
dataString = 'add=' + add1;
$.ajax({
type: "POST",
url: submitLink,
data: dataString,
cache: false,
success: function(data) {

/* My Success Notification Here */
}
});
e.preventdefault();
})


I also tried declaring the variable outside of the function as:

var add1;


That doesn't work either, just comes up as 'undefined'

What can I do to fix this?

Answer

drop the var inside so the variable reference is not locally scoped to the click.

var add1;
$('#Button1').on('click', function(e) {
  add1 = 'yes';
  e.preventdefault();
})
$('#Button2').on('click', function(e) {
  add1 = 'no';
  e.preventdefault();
})
$('#DoneButton').on('click', function(e) {
  submitLink = 'submit.php'
  dataString = 'add=' + add1;
  $.ajax({
    type: "POST",
    url: submitLink,
    data: dataString,
    cache: false,
    success: function(data) {

      /* My Success Notification Here */
    }
  });
  e.preventdefault();
});