JavaScript Function is having issues when dealing with whole numbers

When it comes to my JavaScript function designed to inquire about the number of products a user wants to order, I'm facing some issues. The function should display a message if the user tries to order less than one product and show an alert saying "Ordering (quantity) (product)[s]". Unfortunately, these features aren't working as intended.

I attempted to fix this by implementing a return for the quantity, but all it did was alter the webpage to display the quantity number. However, it did prove that the quantity functionality is functional.

function promptQuantity(product) {
  var quantity = prompt("How many " + product + "s would you like?");
  if (quantity > 1) {
    var plural = "s";
  }
  if (quantity = 1) {
    var plural = "";
  }
  if (quantity < 1) {
    alert("Don't be ridiculous! You can't order less than one " + product + "!");
  }
  if (quantity > 0) {
    alert("Ordering " + quantity + " " + product, plural);
  }
}

My expectation from this function is to send an alert notifying the user about their order quantity of the product, but unfortunately, it only returns as "Ordering 1 (product)".

Answer №1

To start, it is important to use '==' instead of '=' when comparing variables 'a' and 'b' for equality.

Additionally, if you already know that 'a' is greater than 'b', there is no need to check for '==' or '<'. It would be more efficient to utilize an if-else statement (or even a switch). Here is an optimized version:

function askAmount(item) {
  var amount = prompt("How many " + item + "s do you want?");
  var message = '';
  if (amount > 1) {
    message = "Ordering " + amount + " " + item + "s";
  } else if (amount == 1) {
    message = "Ordering " + amount + " " + item;
  } else {
    message = "That doesn't make sense! You cannot order less than one " + item + "!"
  }
  alert(message);
}

askAmount('banana');

Alternatively, you can use a switch statement, although the action may be less clear:

function askAmount(item) {
  var amount = prompt("How many " + item + "s do you want?");
  var message = '';
  switch (true) {
    case amount > 1:
      message = "Ordering " + amount + " " + item + "s";
      break;
    case amount == 1:
      message = "Ordering " + amount + " " + item;
      break;
    default:
      message = "That doesn't make sense! You cannot order less than one " + item + "!";
      break;
  }
  alert(message);
}

askAmount('banana');

Answer №2

The code snippet if (quantity = 1) contains an error, as it performs assignment rather than comparison. This means that the variable quantity will always be set to 1. To fix this, use if (quantity == 1) for proper comparison. Additionally, consider restructuring your code in the following way:

function inquireQuantity(item)
{
    var quantity = prompt("How many " + item + "s do you want?");
    var plural = quantity > 1 ? "s" : "";

    if (quantity < 1)
        alert("You can't order less than one " + item + "!");
    else
        alert("Ordering " + quantity + " " + item + plural);
}

inquireQuantity("T-shirt");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Jquery and Ajax to add information to a database

One of the challenges I'm facing involves a page with three forms, each containing separate variables that need to be inserted into a MySQL database for viewing. My current script is working fine, even though I am aware that `mySql_` is deprecated but ...

Access a file from a specified route within Express

Recently, I created a custom Node module that requires a configuration file in CSV format. My goal is to implement this module within an Express Route module; however, I am encountering difficulties related to the loading of the configuration file. Should ...

Counting down with Jquery when times run out

Seeking assistance with implementing a jquery countdown timer on a webpage. The countdown I am utilizing is available at . My requirement is for the countdown to transition to another date once the current countdown expires. For instance, it should countdo ...

The HTML remains unchanged after making an AJAX request

I have a process where I update a database entry by clicking on a select dropdown. Once I confirm the selection, an AJAX POST request is sent to another view which implements the necessary changes in the database and then redirects back to the previous pag ...

Step-by-step guide for sending data using module.exports in a node.js application

Currently, I am working on implementing a feature that will allow users to input data and store it in a database collection. The technologies I am using for this project are Node.js, MongoDB, Mongoose, Express.js, and AJAX. My goal is to capture user inpu ...

The class may not consistently be assigned to the user when they are positioned at the top of the

Implementing this code allows for different classes to be applied to #nav based on whether the user is scrolling UP, DOWN, or at the top of the page. .nav-down is applied when the user scrolls up .nav-up is applied when the user scrolls down .nav-d ...

Executing a function in AngularJS using PHP

My current project involves an Angular application that needs to load a PHP page within the view. The setup is functioning properly, but I now require an Angular function to run after the PHP code has loaded. I am wondering about the process of calling an ...

The process of passing the ID value to another function is malfunctioning in JavaScript

Currently working on a sudoku puzzle as part of a toy project. My goal is to retrieve the ID value of blank spaces and pass it to another function. However, I am facing an issue where the numbers are not getting inserted into the blanks upon clicking. Can ...

The error message "The property 'find' cannot be found on the data type 'string[]'" indicates that the 'find' method is

While exploring TypeScript, I encountered an error when implementing a find function on a string array: intro.ts:10:19 - error TS2550: Property 'find' does not exist on type 'string[]'. Consider changing the 'lib' compiler op ...

Changing the hover background color and text color of Material UI Button

I recently developed a custom Appbar component using React.js that includes 3 buttons. I'm looking to enhance the user experience by changing the color scheme when users hover over these buttons. Currently, the background color is set to #3c52b2 and t ...

What is the process for implementing a title search filter in Vue.js?

Hey there, hoping you're having a good night! I've been trying to set up a bookstore using Vue.js with code retrieved from a Json api. However, I'm encountering some issues with the "computed" property. Here's the code snippet: new Vue ...

InfoWindow from JSON data not displaying in Google Maps V3

My current project involves using PHP to generate a JSON file from data stored in MySQL. One of the goals I have is to display certain pieces of this data in an information window on Google Maps whenever I click on a marker. Although I've managed to ...

Tips on selectively importing necessary functions/classes from Handlebars

In my Angular application, I am utilizing Handlebars and initially imported it using import * as Handlebars from 'handlebars';. However, I now want to import only specific members of Handlebars like import {registerHelper, compile} from 'han ...

Tips for implementing FontAwesome in Nuxt3

I'm facing some issues trying to implement FontAwesome in my NuxtJS project, and for some unknown reasons, it's not working as expected. Let's take a look at my package.json: { "private": true, "scripts": { " ...

Having trouble with the burger menu not opening while using javascript

Whenever I click the burger_btn, it changes to cross_btn. however, the list menu fails to appear on the screen. In an attempt to debug this issue, I inserted console.log() statements at the beginning and end of both functions. Surprisingly, the console.log ...

Troubleshooting: ngAnimate max-height failing to apply to specific element

Having integrated ngAnimate into a project to enhance animations, I've encountered some unusual behavior with a specific element. Let me provide some context: our website features a shop with categories and products within those categories. I am usin ...

Can you explain the purpose of App.hiddenDivs in jQuery code snippet provided?

Exploring various JQuery performance tips on this insightful website Do you happen to know the significance of App.hiddenDivs ? ...

Using jQuery's setInterval to consistently refresh the value of a data attribute

I am struggling to dynamically update the data-left value of a div with the class name "tw_marquee_scroller" every 1 second. The intended behavior is for the value to increment by 10 each time, starting at 10 and increasing by 10 in subsequent seconds. H ...

Using ServiceStack to deserialize an array

My goal is to post the following data to my ServiceStack web service: $.ajax({ url: 'http://localhost:8092/profiles', type:'POST', data: { FirstName : "John", LastName : "Doe", Categories : [ "Catego ...

Wait until a svelte store value is set to true before fetching data (TypeScript)

I have implemented a pop-up prompt that requests the user's year group. Since I have databases for each year group, I need to trigger a function once the value of userInfo changes to true. My JavaScript skills are limited, and my experience has been ...