SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Sep 2012
    Posts
    1
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Post How to get a button to call a function

    Hey i need some help, im trying to use javascript to add things like money by clicking a button to call on a function. this is what i can come up with if anyone can lead me in the right direction id apreciate it.

    code:
    <!DOCTYPE html>
    <html>
    <body>

    <p>Click the button to add money to your wallet.</p>

    <button onclick="myFunction()">Wallet</button>

    <p id="demo"></p>
    <button onclick="addMoney()">Add</button>
    <p id="add"></p>
    <script>
    function myFunction()
    {
    var $;

    var $=5;

    document.getElementById("demo").innerHTML=$;
    }
    function addMoney()
    {
    var $;
    var t=$+1;
    document.getElementById("add").innerHTML=t;
    }
    </script>

    </body>
    </html>

  2. #2
    SitePoint Enthusiast
    Join Date
    Jul 2011
    Location
    Novi Sad
    Posts
    34
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You are declaring new variable every time a function is called. Also, try avoiding naming your variables '$', because a lot of JS tools/libs use this character as their identifier (ex. jQuery heavily uses $).
    Here is a slightly edited JavaScript for your example:

    Code:
    var wallet = 5; // set initial wallet value to 5
    
    function myFunction()
    {
      document.getElementById("demo").innerHTML = wallet;
    }
    
    
    function addMoney()
    {
      wallet++; // increments by 1
      document.getElementById("add").innerHTML = "New value: " + wallet;
    }


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •