1

I'm trying to have the price show in JavaScript when my button is clicked but it is just showing me my alert. Can anyone tell me where I went wrong? This is my function:

function prompttotalCost() {
    var totalCost;
    var costPerCD;
    var numCDs;
    numCDS = prompt("Enter the number of Melanie's CDs you want to buy");
    if (numCDS > 0) {
        totalCost = totalCost + (costPerCD * numCDs);
        alert("totalCost+(costPerCD*numCDs)");
        totalCost = 0;
        costPerCD = 5;
        numCDs = 0;
    } else {
        alert("0 is NOT a valid purchase quantity. Please press 'OK' and try again");
    } // end if
} // end function prompttotalCost
3
  • 1
    Keep an eye on the area below the edit box. It gives a realtime preview of your post. Commented Mar 31, 2013 at 15:56
  • 4
    Variables need to be outside string literals, remove the " in your alert Commented Mar 31, 2013 at 15:57
  • 1
    Get rid of the quotation marks in your alert with the variables and see if that helps Commented Mar 31, 2013 at 15:58

1 Answer 1

1

The problem is that numCDs is a string, not a number, because prompt returns a string. You can e.g. use parseInt to convert it to a number:

numCDS = parseInt(prompt("Enter the number of Melanie's CDs you want to buy"));

Next thing: You are not assigning a value to totalCost before using it – that's bad. Either change var totalCost; to var totalCost = 0; or change totalCost = totalCost + (costPerCD * numCDs); to totalCost = (costPerCD * numCDs);.

Also, in your alert invocation, you are putting something that you want to be executed as code into a string. Change

alert("totalCost+(costPerCD*numCDs)");

to something like this:

alert("totalCost is "+totalCost);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.