Script to pop up cancel alert box

There's a dilemma with this code - if you click CANCEL the first time the box pops up, it continues to run. I'm unsure of how to make it redirect to the underlying page when clicked on cancel for the first time.

var numero= prompt ("Enter a number")
    var resultado= parImpar(numero);
        alert ("The number "+numero+" is "+resultado );
    
       
    
    function parImpar (numero){
       if (numero %2===0) {
          return "even" ;
       }
       else{
           return "odd" ;
       }
    }
    
    if (window.confirm ("Let's try another number ")){
     var numero= prompt ("Choose");
     var resultado =parImpar (numero);
         alert("The number "+numero+" is "+resultado );
        
    }else{
        
    }
body {
    background-color:pink;
}
h1 {
   font-weight:bold; 
}
p{
   font-weight:bolder ;
   font-family: Garamond;
}
<!DOCTYPE html>
<html>
    <head>
        <title>Page Title</title>
    </head>
    <body>
        <h1>First web! </h1>
            <p>Hi everyone! this is mi first ever page/program. I have been learning for a month now and i need it to understand some javascript functions. Im really fighting with them.</p>
            
    </body>
</html>

Answer №1

In order to prevent executing the following lines of code, make sure to verify if the prompt returns null (indicating that cancel was clicked). Here is an example:

var number = prompt("Enter a number");
if (number !== null) {//Cancel clicked!
      var result = evenOrOdd(number);
      alert("The number "+number+" is "+result);
}

Answer №2

Here is the current state of the code. I'm facing a situation where I need to add a conditional statement, but I'm not quite sure how to go about it. Apologies for the confusion! I've only been learning for a month and I'm finding it quite challenging!!

var numero = prompt("Introduce a number")
if (numero !== null) {//Cancel button clicked!
  var result = checkEvenOdd(numero);
  alert("The number "+numero+" is "+result);
} else {

}

if (window.confirm("Let's try another number")) {
  var newNumber = prompt("Choose a number");
  var result = checkEvenOdd(newNumber);
  alert("The number "+newNumber+" is "+result);
} else {

}

function checkEvenOdd(number) {
  if (number % 2 === 0) {
    return "even";
  } else {
    return "odd";
  }
}

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

Update the link by simply clicking on a div tag

I am currently working on a PHP page and my goal is to add the extension ?id=variable_value to its URL when I click on a specific div. However, whenever I try to do this, it shows me an error message stating that the URL with the extension is undefined. B ...

show information on a separate screen following the selection of a choice

After selecting an option, how can I make #formid appear where the form is filled in with the stock selected in the option section? <div class="form-group"> <label for="exampleFormControlSelect1">Item Name</label> <select clas ...

Encountering the "Error: data.map is not a function" issue within Next.js

I'm having trouble understanding why this first fetch call works perfectly: async function getData() { const res = await fetch('https://jsonplaceholder.typicode.com/todos') return res.json() } export default async function Home() { co ...

Encountering a "Error 404: Page Not Found" message when trying to request a json object from a node server

Working on a RESTful API, I have set it up to run on node.js using express.js, mongodb with mongoose for object modeling, and body-parser for passing HTTP data. However, whenever I start the server and try to access the specified IP address, I encounter a ...

Scrolling the inner container in a CSS flexbox layout: tips and tricks

I'm currently working on designing a flex box based HTML layout like the one shown in the image link provided below. https://i.stack.imgur.com/nBl6N.png The layout should consist of 3 rows within the viewport with the following structure: - top: " ...

A guide to transforming rows into columns with CSS

Hello, I am trying to convert rows into columns using CSS. Currently, my code looks like this: <style> .flex-container { max-width: 500px; width: 100%; display: flex; flex-wrap: wrap; } .flex-item { ...

Tips for dividing HTML code on a page into individual nodes

I am looking to extract the HTML content from a website and then parse it into nodes. I attempted the following code: function load() { $(document).ready(function () { $.get("https://example.com/index.html", function (data) { const loadpage ...

Display the mobile keyboard without the presence of an input element

Attempting to display the mobile keyboard on my responsive site, I initially tried placing a hidden input with the placeholder "tap here." However, due to an event firing on this input that reloads the dom, I was unable to show the keyboard. I'm wond ...

jquery function context

I'm having trouble grasping function scope in this scenario. When a button is clicked, it triggers a dialog box with a textarea inside displaying a URL that can be copied for camera setup. <button id="axis-details" onclick="apikey('<?php e ...

The admin-ajax.php file in WordPress consistently fails to return any value other than

I developed a WordPress ajax plugin, but I am facing an issue where admin-ajax.php always returns 0 and the plugin doesn't work as expected. Here is the code I have implemented: add_action( 'wp_ajax_example_ajax_request', 'example_aja ...

Vue js is throwing an error message that says "Reading 'push' property of undefined is not possible"

I've encountered an issue while trying to navigate to other routes. The error I'm receiving is: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'push') at eval (JoinRoom.vue?bd9d:74:1) This is how I pu ...

Having trouble getting Firebase phone number authentication to work with Vue.js

I am currently in the process of developing a new Vue.js application using the Webpack template. Within this app, I have implemented a /sign-in route that displays a component named SignIn. To authenticate users, I am utilizing Firebase Phone Number authen ...

Concealing the ellipsis in the will_paginate function of Rails

I'm currently utilizing will_paginate to manage a large number of values, but I am struggling to find a way to hide the "..." portion and the page numbers following it. Here is my current setup: https://i.stack.imgur.com/f2Tt8.jpg However, what I wou ...

Is it possible to merge two HTML selectors using jQuery?

In my HTML, I have two button elements defined as follows: <input type="button" class="button-a" value="Button a"/> <input type="button" class="button-b" value="Button b"/> When either of these buttons is clicked, I want to trigger the same ...

Utilizing Node.js and Express.js to Parse HTML Form Inputs

Having trouble extracting input from an HTML form and utilizing it in Node.js. Here is the HTML form being used: <form action="/myform" method="POST"> <input type="text" name="mytext" required / ...

Check to see if the property of the object does not exist within the array and update as

My goal is to add the variable content into the database content using the $push method, but only if the content.hash doesn't already exist in the database. I want to avoid duplicating information unnecessarily. return shops.updateAsync({ "user": u ...

Is it possible to uncheck a checkbox from a list, even if some of them are already unchecked?

I am attempting to implement a feature where checking a checkbox selects all others in the list, and unchecking one deselects all. Currently, only selecting one checkbox allows me to check all the rest, but unchecking one doesn't trigger the reverse a ...

The script is malfunctioning on Google Chrome

Below is a script that I have: EXAMPLE : <script> var ul = document.getElementById("foo2"); var items = ul.getElementsByTagName("li"); for (var i = 0; i < items.length; i=i+2) { // perform an action on items[i], which repr ...

Displaying a collection of items using Rails, implementing form_for and integrating Ajax functionality

Looking to display a list of "Interests" for users to "follow" by clicking on a button linked to the Interest's image. Once the follow button is clicked, the Interest and its image should be removed from the list. Attempting to use a hide function in ...

Tips for modifying a biography with PHP

I'm working on a feature that allows users to edit their biography. I want the text stored in the database to show up in the text box, rather than just as a placeholder. How can I achieve this? Currently, the text is set as a placeholder, but my goal ...