[Solved] Why wont my function run onclick?


There were numerous issues with your code, starting with your JSFiddle configuration, moving on to how none of your functions are declared or invoked properly:

You have:

function(addNickel){
    var availableCredit = availableCredit + 0.05;
}

and:

 onclick="function(addNickel)"

Both of these are putting the function name in the parenthesis instead of before it. The code should be:

function addNickel(){
    var availableCredit = availableCredit + 0.05;
}

and:

 onclick="addNickel()"

All your function declarations and calls are like this and need to be updated.

And, errors with semi-colons in places they shouldn’t be and using prompt when alert was needed to doing math but then not storing the answer anywhere. Leading up to the gobs and gobs of redundant code. You don’t need a math function to update the totals in stock or the amount on hand for each soda. Just make one function and pass in an argument that the math can work with. The general rule of thumb is “Isolate what changes from what doesn’t”. Your algorithms don’t change from soda to soda, only the amount does.

This still needs a little cleaning up, but here is a working version that has the redundant code removed and syntax cleaned up:

$(function(){

  var sodaTotals = [10, 10, 10, 10];

  var cashOnHand = 40;
  var currentCredit = 0;

  var rootBeerTotal = document.getElementById('root_beer_instock');
  var pepsiTotal = document.getElementById('pepsi_instock');
  var orangeTotal = document.getElementById('orange_instock');
  var mtDewTotal = document.getElementById('mt_dew_instock');

  // Put HTML elements into an array that maps to the sodaTotals array
  var stock = [rootBeerTotal, pepsiTotal, orangeTotal, mtDewTotal];

  var machineFunds = document.getElementById('funds');
  var availableCredit = document.getElementById('available_credit');

  // Get Button references:
  var $btnNickel = $("#nickel");      
  var $btnDime = $("#dime");         
  var $btnQuarter = $("#quarter");         
  var $btnDollar = $("#1_dollar");           
  var $btn5Dollar = $("#5_dollar");

  var $btnRB = $("#root_beer");
  var $btnPep = $("#pepsi");
  var $btnOr = $("#orange");
  var $btnDew = $("#mt_dew");

  var $btnReload = $("#reload_soda");
  var $btnReset = $("#reset_COH");

  // Wire up event handlers for buttons. Each handler will call the single math function
  // but pass it the correct amount to modify the amount by
  $btnNickel.on("click", function(){ adjustPrice(.05); });
  $btnDime.on("click", function(){ adjustPrice(.1); });
  $btnQuarter.on("click", function(){ adjustPrice(.25); });
  $btnDollar.on("click", function(){ adjustPrice(1); });
  $btn5Dollar.on("click", function(){ adjustPrice(5); });

  // Array indexes start from 0, not 1
  $btnRB.on("click", function(){ dispenseSoda(0); });
  $btnPep.on("click", function(){ dispenseSoda(1); });
  $btnOr.on("click", function(){ dispenseSoda(2); });
  $btnDew.on("click", function(){ dispenseSoda(3); });
  
  $btnReload.on("click", reloadSoda);
  $btnReset.on("click", resetCOH);

  // Money stuff
  //Don't declare the variables in the functions because that will wipe out the old values
  var credit = null;
  
  // You don't need a function for each transaction, just pass the value that needs to be adjusted
  function adjustPrice(amount){
    credit += amount;
    availableCredit.textContent = credit.toFixed(2);
    machineFunds.textContent = credit.toFixed(2);
  }

  // Reset tools
  function reloadSoda(){
      sodaTotals = [10, 10, 10, 10];
  }

  function resetCOH(){
      cashOnHand = 40;
      alert("You reach into the machine and pull out what appears to be Monopoly money. Make it rain!");
  }

  // Each function represents a different flavor represented as 'dispenseFlavor'
  function dispenseSoda(flavorIndex){

    if (credit >= 0.5) {
    
      // Deduct stock amount
      sodaTotals[flavorIndex]--;
      stock[flavorIndex].textContent = sodaTotals[flavorIndex];

      // Deduct funds
      credit -= 0.50;
      document.getElementById('available_credit').textContent = credit.toFixed(2);
      
      // Add to machine's balance  
      cashOnHand += 0.50;

      alert('Please pickup your soda from below. Thank you for your purchase!');

      // Check if user has any additional money in machine
      if(credit > 0){ 

        if (confirm("Would you like to make another purchase?")) {
             alert("Please select another soda.");
        } else {
             alert('Please collect your refund below.');
             document.getElementById("refund_tray").innerHTML = credit;
             var availableCredit = 0;
        }

      } else {
        alert('Insuficient funds, please add additional funds.');
      }
    }
  }

 });
.site-title {
     font-size: 3rem;
     font-color: rgb(200, 200, 200);
 }
 
 .current-levels { width: 20%; }
 
 .payment-container {
     width: 75%;
     border: solid black 2px;
 }
 
 .payment {
     display: flex;
     flex-direction: row;
     justify-content: space-around;
 }
 
 .payment-container p { text-align: center; }
 
 .button-region-container { border: solid black 2px; }
 
 .button-container button {
     height: 5rem;
     width: 12%;
     background-size: contain;
     background-repeat: no-repeat;
 }
 
 button#root_beer { background-image: url('http://full.nick2go.com/img/root-beer.jpg'); }
 button#pepsi { background-image: url('http://full.nick2go.com/img/pepsi.jpg'); }
 button#orange { background-image: url('http://full.nick2go.com/img/orange.jpg');  }
 button#mt_dew { background-image: url('http://full.nick2go.com/img/mt-dew.jpg'); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="site-title">
        <h2>Gasia's Soda Machine</h2>
    </div>
    <div class="payment-container">
    <div class="credit-container">
        <p>Funds in the Machine: <span id="funds"></span></p>
        <p>Available Credit: <span id="available_credit"></span></p>
        <p>Refund Tray:<span id="refund_tray"></span></p>
        <p>Click the below buttons to insert money into the machine:</p>
        <div class="payment">
            <button type="button" id="nickel">$0.05</button>
            <button type="button" id="dime">$0.10</button>
            <button type="button" id="quarter">$0.25</button>
            <button type="button" id="1_dollar">$1.00</button>
            <button type="button" id="5_dollar">$5.00</button>
        </div>
    </div>
    <div class="button-region-container col-xs-12">
        <p class="button-title">Select a soda from below:</p>
        <div class="button-container">
            <button id="root_beer" alt="root beer"></button>
            <button id="pepsi" alt="pepsi can"></button>
            <button id="orange" alt="orange can"></button>
            <button id="mt_dew" alt="mt-dew can"></button>
        </div>
    </div>
    <div class="current-levels .col-xs-6">
        <div class="flex-soda-total" id="rootbeer_stats">
            <p id="root_beer_title">Number of cans of Root Beer remaining:<span id="root_beer_instock">10</span></p>
        </div>
        <div class="flex-soda-total" id="rootbeer_stats">
            <p id="pepsi_title">Number of cans of Pepsi remaining:<span id="pepsi_instock">10</span></p>
        </div>
        <div class="flex-soda-total" id="rootbeer_stats">
            <p id="orange_title">Number of cans of Orange remaining:<span id="orange_instock">10</span></p>
        </div>
        <div class="flex-soda-total" id="rootbeer_stats">
            <p id="mt_dew_title">Number of cans of Mt. Dew remaining:<span id="mt_dew_instock">10</span></p>
        </div>
    </div>
    <div class="admin-tools">
        <p>The button on the left will reset the soda stock, back to default levels. The button on the right will withdraw all the money from the machine. Choose wisely.</p>
        <button id="reload_soda">Refill Soda Machine</button>
        <button id="reset_COH">Rob The Machine!</button>
    </div>

6

solved Why wont my function run onclick?