anatp_123
anatp_123

Reputation: 1205

How to access value of a variable depending on select option?

I have a SELECT option that depending on the selected value I want to change the value of a varible NumberHoliday.

How do I access the value of the variable in another function?

var NumberHoliday;
var finalTotal;

$(function() {
  $(document).on("change", "#deptType", function(e) {
      var totalValue = $('#deptType').val();

      if(totalValue == "Fraud"){
         NumberWeekValueFraud();

      }else{
       NumberWeekValueOther();
      }

  });
});

function NumberWeekValueFraud(){
  var NumberHoliday = 25.00;
  $('#totalDays2').val(NumberHoliday);
  return NumberHoliday;
}

function NumberWeekValueOther(){
  var NumberHoliday = 50.00;
  $('#totalDays2').val(NumberHoliday);
  return NumberHoliday;
}

function CountTotal(el){
   if(el.checked) {
       //use NumberHoliday here once checkbox is check,  depending on the select option value
}

Upvotes: 0

Views: 53

Answers (3)

Danilo Carrabino
Danilo Carrabino

Reputation: 397

Your variable NumberHoliday is a global variable, so you can access it directly from your functions in this way:

var NumberHoliday = 0;
var finalTotal = 0;

$(function() {
  $(document).on("change", "#deptType", function(e) {
  var totalValue = $('#deptType').val();


       if(totalValue == "Fraud"){
          NumberWeekValueFraud();

       }else{
        NumberWeekValueOther();
       }


});

  });

function NumberWeekValueFraud(){
  NumberHoliday += 25.00;
  $('#totalDays2').val(NumberHoliday);
}



function NumberWeekValueOther(){
  NumberHoliday += 50.00;
  $('#totalDays2').val(NumberHoliday);
}



function CountTotal(el){
   if(el.checked) {
    console.log("Total: " + NumberHoliday);
       //use NumberHoliday here once checkbox is check,  depending on the select option value
       }
}

Upvotes: 0

bigbounty
bigbounty

Reputation: 17408

One workaround is to make the variable global. Another workaround is to write a separate function, in order to return the value of the variable inside the function and call it. Another workaround is to pass functions as in functional programming languages.

Upvotes: 0

guest271314
guest271314

Reputation: 1

You can pass the function to the function

function CountTotal(el, fnValue){
   if (el.checked) {
   // do stuff with `fnValue`
   }
}

CountTotal(/* el */, NumberWeekValueFraud());

CountTotal(/* el */, NumberWeekValueOther());

Upvotes: 1

Related Questions