SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    Feb 2004
    Location
    Body
    Posts
    53
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Addition instead of concatination

    I have a form and two functions. Function 1 grabs the total amount of credits a user has, and function 2 uses javascript to dynamically add and subtract from the users credits based off of elements the end user manipulates on a form. For instance, if function 1 says the user has 15 credits available, and they select an option from a form worth 1 credit, the screen updates that they have 14 credits remaining. However, if the end users deselects that option costing 1 credit, then javascript adds the 1 credit back into their bank, for 15 total credits again.

    My problem appears that I can subtract from a credit pool just fine, but when I add it back in, javascript has apparently turned my integer into a string, and thus concatinates it.

    Here is my add/subtract function:

    function credits(creditCost){
    //if it's disabled and they have enabled it, subtract credits
    if (document.pre.creditType1.disabled==true){
    document.pre.creditType1.disabled=false;
    //retrieve the number of credits they have currently (already populated elsewhere)
    var currentCredits=document.getElementById('testing').innerHTML;
    var newCredits=currentCredits-=creditCost;
    //update the cells with he new value
    document.getElementById("testing").innerHTML=newCredits;
    } else
    {
    //selection is already active and they have deselected it.. add credits back
    document.pre.terrainType.disabled=true;
    //retrieve the number of credits they have currently and add the cost back
    var currentCredits=document.getElementById('testing').innerHTML;
    var newCredits=currentCredits+=creditCost;
    //update the cells with he new value
    document.getElementById("testing").innerHTML=newCredits;
    }
    }


    The problem that I'm having is that I can subtract fine.. but I cannot add. For instance, if a user has 15 credits, selects an option costing 1, then the screen correctly updates to 14 remaining credits. However, if the user deselects that option, then the cost is not added back, but concatinated... so instead of returning to a value of 15, I then get 141 ("14" + "1").

    Javascript newbie here.. any help would be appreciated. Thanks.

  2. #2
    SitePoint Zealot
    Join Date
    Jul 2008
    Posts
    140
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Try using the parseInt() function


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
  •