Help a noob out with some simple java script

I can’t seem to get my second if else statement to work. I am incredible new to this javascript stuff. I’m sure its something down right easy to do but its gone straight over my head. Thanks guys :slight_smile:

<script>
function ticket_cost(price_each)
  

{

var sum;
var total;



sum = prompt("How many tickets? Maximum number of tickets is 8.", "");

quantity = Number(sum);

total = quantity * price_each;

{if ((sum <=8) && (sum>=1))

{alert ("Please enter a valid number of tickets. The maximum number of tickets is 8"); }

else{
if (confirm("You ordered " + sum +  "tickets" + " at " + "$" + price_each + " for a total ticket cost of  " + "$" + total.toFixed(2) +" To confirm these tickets press ok. to release these tickets press cancel" )

  
alert("thank you your order has been recived. See you at the show!")

else if{

{alert("your tickets have been released. Come again soon!")

}
}

</script>

Room for improvement here, but hopefully a few pointers.

var ticketCost = function (priceEach) {

  // Defining my local variables here. Separated with commas.
  var numTickets,
      total,
      order = ''
      orderStatus = false,

  getSum = function() {

    // wrap the response inside parseInt so as to convert it to a number.
    var val = parseInt(prompt('How many tickets? Maximum number of tickets is 8.', ''));

    // Using x ||(or) y to check for an invalid number
    // calling getSum again until a valid number is entered.
    // Note: Already mention how many tickets are required so removed the alert.
    if ( val>=8 || val<1 ) {
      return getSum();
    }

    return val; // return total tickets

  };
  // End of variable definitions finished off with a semi-colon.

  numTickets = getSum();
  total = (numTickets * priceEach).toFixed(2);
  order = 'You ordered ' + numTickets + ' tickets at $' + priceEach + ' each.\
 Total price is $' +
           total + '.\
\
 Press OK to confirm order or CANCEL to decline. ';
  // A boolean of true is returned if OK is pressed or false if cancelled.
  orderStatus = confirm(order);

  if ( orderStatus === true ) {
    alert("Thank you for your order it has been received. See you at the show!");
  } else {
    alert("Your tickets have been released. Come again soon!");
  }

};

ticketCost(20);

Minus comments

var ticketCost = function (priceEach) {

  var numTickets,
      total,
      order = ''
      orderStatus = false,

  getSum = function() {

    var val = parseInt(prompt('How many tickets? Maximum number of tickets is 8.', ''));

    if ( val>=8 || val<1 ) { return getSum(); }

    return val;

  };

  numTickets = getSum();
  total = (numTickets * priceEach).toFixed(2);
  order = 'You ordered ' + numTickets + ' tickets at $' + priceEach + ' each.\
 Total price is $' +
           total + '.\
\
 Press OK to confirm order or CANCEL to decline. ';
  orderStatus = confirm(order);

  if ( orderStatus === true ) {
    alert("Thank you for your order it has been received. See you at the show!");
  } else {
    alert("Your tickets have been released. Come again soon!");
  }

};

ticketCost(20);
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
  <title></title>
</head>

<body>
<script>
function ticket_cost(price_each){
 var sum= prompt("How many tickets? Maximum number of tickets is 8.", "");;
 var total = sum * price_each;
 if (sum>8||sum<1){
  alert ("Please enter a valid number of tickets. The maximum number of tickets is 8");
 }
 else if (confirm("You ordered " + sum +  "tickets" + " at " + "$" + price_each + " for a total ticket cost of  " + "$" + total.toFixed(2) +" To confirm these tickets press ok. to release these tickets press cancel") ){
  alert("thank you your order has been recived. See you at the show!");
 }
 else {
  alert("your tickets have been released. Come again soon!");
 }
}
ticket_cost(1.5);
</script>
</body>

</html>

prompt, confirm and alert were re-purposed for debugging when Netscape 4 died and it became possible to actually update the web page itself. More recently they have effectively become obsolete now that all browsers have a built in debugger.Some people now have one or more of those turned off in their browser because they are annoying - although checking the box they display for turning off JavaScript to stop debugging is only two clicks more than having it completely disabled.

parseInt() is not the correct function for converting a string to a number - the correct function to do that is Number()

Whatever source you are using to try to learn JavaScript appears to be about 15 years out of date.

Interested in that point. Haven’t seen it raised before.

If I were to use parseInt then specifying the base parseInt(string,10) would have been better, but why not parseInt in the first place? Does seem to be commonly used.

I know as an alternative you can use the unary operator +‘number’ or bitwise or (‘number’|0).

For number you would want to use Number(String).toFixed(0)? Yes?

Regards the other points, had a feeling that was the case. Looked up ‘confirm’ expecting to see mention of it being obsolete. Just thought a few pointers at this stage without going into working the DOM if that’s what’s required would help.

No - the toFixed coded that way converts it back to a string.

Using the unary + operator makes an implicit call to Number() and so +string and Number(string) are identically equivalent.

If you want an integer then it depends on whether you just want to discard the fraction part or to round to the nearest integer.

Math.floor(string) would provide the integer part discarding the fraction (as that method expects a number it would implicitly convert the string to a number first).

Math.round(string) would round the number entered to the nearest integer.

In each of these specifying a string that did not contain just a number would result in the string being converted to 0.

As you said using parseInt() really needs 10 specified in the second parameter for it to work correctly. Of course using parseInt(‘0xff’,10) works quite well for returning the number equivalent of the original string (255 in this case) but the only benefit it gives over the more efficient calls that just convert the string to a number is where you have people entering all their numbers in hexadecimal and you want the parseInt to convert them to decimal. How many of your visitors do you expect will enter their numbers in hexadecimal so as to require the additional overhead of using parseInt to convert them?

Thanks for that Felgall, very useful to know. So essentially Number is more efficient.

How many of your visitors do you expect will enter their numbers in hexadecimal so as to require the additional overhead of using parseInt to convert them?

Good point. One use I can possibly think of though and not necessarily form material would be in converting hex colours to rgb equivalents. There are however some nifty bitwise alternatives. e.g. (‘0xC0’ & 0xFF) –> 192

Cheers

That sounds like a contradiction in terms. The function/feature prompt lets the user enter a value which can be used directly. For example, if the user omitted to enter an email address in a form. That saves the user a few steps. And there has been no such thing as “re-purposing”.

That’s baloney. They have their own and very different uses from debugging. The use of alert we all know, and confirm returns a boolean true of false, with which two different actions can follow. For example, go to another page/site, or stay on the current one. And there are many other useful things that you can do with it. The fact that some web devs (only know how to) use alert for Javascript debugging, while the console offers much more functionality, is a very different matter. Especially because the OP doesn’t it as such at all.

That may be so. But then they will miss out on alerts/confirms like “With the option you ticked, the shipping costs will be double that of normal shipping. Are you sure you want that?” And chances are that forms won’t function at all with those turned off.

That’s baloney with pickles. They are still part of the latest ECMA standards, and are supported by the most modern browsers, without any problem whatsoever. The OP is making very proper use of the functions/features. The only thing you are doing with your comment is making him/her insecure.

w3schools is run by two guys who tried to cover too many subjects. Their web site is way out of date - particularly the JavaScript section (although they did recently start updating some of the 15+ year out of date pages).

If a prompt wasn’t repurposed for debugging use only then why does it always display a checkbox for disabling JavaScript on the current page as in the below image?

So… I think this needs more explanation. I think felgall came out with the right answer but for the wrong reasons.

RLM2008, you’re right that parseInt() works perfectly well (with the base argument). It was suggested that using Number() is more efficient, though there wasn’t any evidence supplied to back this up. I googled for performance tests, and it looks like parseInt() may actually be faster than Number(). In fact, in recent versions of Chrome, it looks like other options such as the unary plus blows them both out of the water.

But… keep in mind that these differ from each other only in nanoseconds. These are micro-optimizations that won’t have any real-world impact on your app, so don’t sweat it.

Yet I still agree that Number() is a better choice than parseInt(). Why? It doesn’t have anything to do with efficiency (obviously). It has to do with usability. If a user gives you bad input, such as 9xwnu2gD, then you could either try to extract some number from that and compute what will undoubtedly be a junk result, or you could alert the user that they made a mistake and instruct them how to fix it. I think the latter is better. parseInt() will achieve the former; it will extract the number 9 from that bad input. Number() will achieve the latter; it will return Not A Number.

Yet I still agree that Number() is a better choice than parseInt(). Why? It doesn’t have anything to do with efficiency (obviously). It has to do with usability. If a user gives you bad input, such as 9xwnu2gD, then you could either try to extract some number from that and compute what will undoubtedly be a junk result, or you could alert the user that they made a mistake and instruct them how to fix it. I think the latter is better. parseInt() will achieve the former; it will extract the number 9 from that bad input. Number() will achieve the latter; it will return Not A Number.

That’s a great reason to use Number. Thanks a lot for the info.

RLM

Here, you are basically just repeating your statement, without giving any arguments as to why you would be right/up-to-date and they would be wrong/out-of-date.

So because a browser offers the possibility to block further prompts, prompts have re-purposed for debugging use – even for debugging use only? What kind of logic is that??

That was a too bold statement. The OP is making technically proper use of the functions/features. Whether his/her use of the prompts, etc. contributes to a good user experience may be questioned. I wonder why s/he doesn’t use normal form fields, and use the said matters only for validation purposes.

So Number() is more efficient at determining whether the value is a number or not than parseInt() is.

I never said it is faster.There are a lot more aspects to efficiency than just speed.

Regards the OP the poor guy never returned.

So Number() is more efficient at determining whether the value is a number or not than parseInt() is.

I never said it is faster.There are a lot more aspects to efficiency than just speed.

It was me who jumped to that conclusion. I did take your comments with regards efficiency and ParseInt’s overheads to mean something along those lines.

Either way can certainly see the plus side to using Number with regards how it handles garbage values. Easier for debugging at the very least.