Detecting if a value is less than zero

I wrote a bank script that verifies if the user's deposit amount is a positive integer. If it's not, I want to reject the transaction.

Check out my code snippet below:

<section id="pigBox">
      <img src="images/pig.png" />
      <label>Balance: </label><input type="text" id="balance" />
      <button id="deposit"> Deposit </button>
      <button id="withdraw"> Withdraw </button>
  </section><!-- end of pigBox-->

document.getElementById('balance').value = "1000"

var balance = document.getElementById('balance').value;
var deposit = document.getElementById('deposit');
var withdraw = document.getElementById('withdraw');

deposit.addEventListener('click', depositCash);
withdraw.addEventListener('click', withdrawCash);

function depositCash() {
  var depositAmt = prompt('How much would you like to deposit?');

  if(depositAmt !== Number(depositAmt) && depositAmt) {
    return alert('Please enter a valid integer.');

  }
  balance = Number(balance) + Number(depositAmt);
  document.getElementById('balance').value = balance;
}

function withdrawCash() {
  var withdrawAmt = prompt('How much you you like to withdraw?');

  if(withdrawAmt !== Number(withdrawAmt)) {
    return alert('Please enter a valid integer.');

  }
  balance = Number(balance) - Number(withdrawAmt);
  document.getElementById('balance').value = balance;
}

I attempted to address the issue with ..

else if(Number(depositAmt) < 0) {
 return alert('please enter a valid integer.');
}

However, this method did not work as expected. Can anyone provide insight into what I might be doing incorrectly?

Thank you in advance!

Answer №1

Ensure to validate

if (depositAmt <= 0) {
    return alert('Please input a positive number.');
  }

Modify your if statement to include else if and else for better efficiency.

 if (depositAmt != Number(depositAmt) && depositAmt) {
    return alert('Please input a valid number.');

  } else if (depositAmt <= 0) {
    return alert('Please input a positive number.');

  } else {
    balance = Number(balance) + Number(depositAmt);
    document.getElementById('balance').value = balance;
  }

document.getElementById('balance').value = "1000"
var balance, inputDeposit, inputWithdraw;
balance = document.getElementById('balance').value;
inputDeposit = document.getElementById('deposit');
inputWithdraw = document.getElementById('withdraw');

inputDeposit.addEventListener('click', makeDeposit);
inputWithdraw.addEventListener('click', makeWithdraw);

function makeDeposit() {
  var depositAmt;
  depositAmt = prompt('How much would you like to deposit?');

  if (depositAmt != Number(depositAmt) && depositAmt) {
    return alert('Please input a valid number.');

  } else if (depositAmt <= 0) {
    return alert('Please input a positive number.');

  } else {
    balance = Number(balance) + Number(depositAmt);
    document.getElementById('balance').value = balance;
  }
}

function makeWithdraw() {
  var withdrawAmt;
  withdrawAmt = prompt('How much would you like to withdraw?');

  if (withdrawAmt != Number(withdrawAmt)) {
    return alert('Please enter a valid number.');

  }
  balance = Number(balance) - Number(withdrawAmt);
  document.getElementById('balance').value = balance;
}
<section id="pigBox">
  <img src="images/pig.png" />
  <label>Balance: </label><input type="text" id="balance" />
  <button id="deposit"> Deposit </button>
  <button id="withdraw"> Withdraw </button>
</section>
<!-- end of pigBox-->

Answer №2

To verify, follow these steps:

if(isNaN(Number(depositAmt)) || Number(depositAmt) < 0) {
    return alert('Kindly input a correct whole number.');
}

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

Is there a way to activate a function in one component from another within a Next.js application?

As mentioned in the title, I am working with 2 custom components within a basic NextJS application: <section> <CompA></CompA> <CompB></CompB> </section> I am trying to figure out how to have a button inside Comp ...

Executing an external JavaScript function from within an internal JavaScript code block

Currently, I am dealing with 2 JavaScript blocks. One is contained within my HTML and handles touch functionality, while the other is an external file serving as a content slider. My goal is to utilize touch events to control the slider - allowing users to ...

Update my React shopping cart with fresh items

I am currently dealing with an issue in my online food ordering system. Specifically, when I click on the add button to order an item, it updates the existing item in the cart instead of appending the new one as the next item. Highlighted below is a cruci ...

Tips for transforming a nested array of arrays into a string separated by commas

Currently, I have an object that contains 2 nested arrays. Both of these arrays are array of arrays and I am looking to combine their values into a comma-separated string. I am exploring options in JavaScript, jQuery, or linq.js to accomplish this task. Wh ...

Enable automatic playback of HTML5 video with the sound on

I want to add an autoplay video with sound on my website, but I'm running into issues with newer browsers like Chrome, Mozilla, and Safari blocking autoplay if the video doesn't have a 'muted' attribute. Is there a clever HTML or Javas ...

What is the process for uploading files using AngularFire on Firebase Storage?

Despite watching multiple videos and tutorials, I am encountering a 403 error while working with Angular 1. To solve the issue of ng-model not supporting files, I created an Angular directive named file-model: app.directive('fileModel',['$ ...

Unable to transfer AJAX data to PHP script

Trying to figure out how to send AJAX data to PHP. While I am comfortable with PHP, JavaScript is a bit new to me. Incorporating HTML / JavaScript <input type="text" id="commodity_code"><button id="button"> = </button> <script id="s ...

Combining arrays in Javascript that share the same key by utilizing a loop

Can you advise on the most effective method to restructure an array for desired output? My goal is to combine all key values, whether in arrays or not, into objects with the same name key. Here is my current array: brands: [ 0:ZARA: {product: "ZARA Blac ...

Utilizing JavaScript filtering logic in Angular Filter with AngularJS

This inquiry originates from this source Within the realm of Javascript, I have crafted a code to facilitate filtering, specifically showcasing elements from the array colors only if they correspond as values in cars. var colors = ["blue","red","pink","y ...

Implementing JSON response in email functionality using Ajax and PHP

I've encountered a problem with my contact form. I'm receiving error messages for invalid email and incomplete fields, but I'm not getting a success message. As a result, the email is being sent twice without any confirmation message (I&apos ...

Error occurred while attempting to run 'postMessage' on the 'Window' object within GoogleTagManager

Recently, I encountered an error stating "postMessage couldn't be cloned". This issue seems to be affecting most of the latest browsers such as Chrome 68, Firefox 61.0, IE11, and Edge. Error message: Failed to execute 'postMessage' on &ap ...

Can importing a library generate a fresh copy of the imported library?

In my development setup using webpack and vue-loader to build a Vue.js application, I have various .vue files for different components. Whenever I include the line: import _ from 'lodash' in the script section of both ComponentA.vue and Compone ...

Developing Reactive Selections with Material-UI is made easy

After spending about 5 hours on a task that I thought would only take 15 minutes, I still can't figure out the solution. The issue is with my React App where I have two dropdowns in the Diagnosis Component for users to select Make and Model of their a ...

Tips for adjusting the dimensions of material table within a react application

Could someone please provide guidance on adjusting the size of a table made with material table? I am currently working in React and the following code is not yielding the desired outcome. I even attempted to use 'react-virtualized-auto-sizer' wi ...

The next button will only activate once all input forms have been completed in multiple forms

In the JavaScript code: var current_fs, next_fs, previous_fs; //fieldsets var left, opacity, scale; //fieldset properties that will be animated var animating; //flag to prevent rapid glitches from multi-clicking $(".next").click(function(){ if(animati ...

javascript utilizing key inputs

Is there a way I can create a function that activates when the "A" key on my keyboard is pressed, sending a signal to nupp('/TS'), and stops sending the signal when the "A" key is released? <html> <head> <script src=\"htt ...

Performing the task of removing a complete script using D3 or JavaScript

Here is the current setup I have in my code: The index.html file contains <div id="div1"></div> and I dynamically load a file into it (when a socket arrives) using this script: <script> var socket = io.connect('http://127.0. ...

Why isn't the length of the Array changing when using React's useState hook

I am facing a challenge trying to understand why the value of inputElementArray.length consistently remains 0 when accessed within the useEffect method. function view() { const [inputElementArray, setInputElementArray] = useState<HTMLInputElement[]& ...

Encountering an error with NextJs & Strapi when utilizing the getStaticPaths functionality

Currently, my project involves using Strapi to develop a custom API and NextJs for the frontend. I am experimenting with utilizing getStaticPaths to generate pages based on different categories. In Strapi, I have set up a collection for categories that is ...

Ways to obtain a tab and designate it as the default in angular when using angular material Tabs

I am facing an issue with accessing tabs within a nested component. The parent component contains the tab feature and to reach the tabs inside the child component, I am using the following code: document.querySelectorAll('.mat-tab-group'); The a ...