Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I pass a value to a function in JavaScript?

I have this code that changes the value of a variable called "factor" based upon a dropdown list selection:

sel.addEventListener("change", function (evt) {
      var days = parseInt(evt.target.options[evt.target.selectedIndex].value);
      var factor = 0;
       switch (days) {
        case 3: case 4: var factor = 1.5; break;
        case 5: case 6: var factor = 1.4; break;
        case 7: case 8: case 9: var factor = 1.3; break;
        case 10: case 11: case 12: case 13: case 14: var factor = 1.2; break;
        case 15: default: var factor = 1.0;
      }

Then, I have this function that is supposed to use the variable called "factor" in a calculation based upon another (different) dropdown list selection:

psel.addEventListener("change", function (evt) {});
     function calculate (pfactor){
     var nopages = document.getElementById("pages");
     var priceOutput = document.getElementById("nopagesOutput");
     var pfactor = document.getElementById("factorOutput");
     priceOutput.innerHTML = nopages.value;

     var total = nopages.value * 10 * factor;
     document.getElementById("savings").innerHTML = `$ ${total}`;

I keep getting NaN as the result. How do I use the value in the variable called "factor" in the calculate(); function?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The factor variable is declared local to the sel change event, so is not visible in the psel event. You need to declare the factor variable outside of the event methods, or save to a hidden input type in sel, and get it from hidden input in psel. Plus you just need the one var declaration, in the switch you don’t need the var keyword, since factor has already been declared (var factor = 0)

In html

<input type="hidden id ="factor"/>

at bottom of sel

document.getElementById("factor").value = factor;

In psel

var factor = document.getElementById("factor").value 

or just declare

var factor = 0 

outside of the events (depending how your code is structured)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading