JavaScript - utilizing a confirmation dialog box within a function

My JavaScript code was working well because I received some fantastic solutions here yesterday. I am now wondering if I can enhance this JavaScript with another query. Currently, the query triggers an alert when the number is greater than 199, and it is functioning perfectly.

Now, I am curious to know if I can implement a confirm box for the same input box when I type in a number larger than 100. For instance, if I input the number 110, I would like a confirm box to appear with some information, and if I click Yes, the number should remain in the input box. However, if I enter 200 or a number larger than that, I should still receive the alert notifying me that the number is too big.

Below is the code that I received yesterday for triggering an alert when the number is greater than 199:

    <!DOCTYPE html>
    <html lang="en">
        <head>
        <meta charset="utf-8">
        <title>Page</title>
    <script type="text/javascript">
    function minMax() {
       var min = 0;
       var mid = 99;
       var max = 199;
       var num = parseInt(document.getElementById('value_one').value);
       if (num > mid && num < max) {
           var r = confirm(num + ' n\'is greater than ' + mid+ '. Press Yes to retain it.');
           if (r == false) document.getElementById('value_one').value = "";
           return false;
       }
       if (min > num || max < num) {
           alert(num + ' n\'is not between ' + min + ' and ' + max);
           return false;
       }       
    </script>
        </head>
        <body>
        <form>
            Value: <input type='text' id="value_one"  onBlur="minMax();">
        </form>
    </body>
    </html>

Is it feasible to incorporate a confirm box for numbers larger than 100? Any ideas are welcome!

Answer №1

Instead of using the alert function, you can utilize the confirm box. Take a look at the demonstration on w3school.

Give this a shot

<script type="text/javascript>
   function minMax() {
       var min = 0;
       var mid = 100;
       var max = 199;
       var num = parseInt(document.getElementById('value_one').value);
       if (num > mid && num < max) {
           var r = confirm(num + ' n\'is greater than ' + mid+ '. Press Yes to retain it.');
           if (r == false) document.getElementById('value_one').value = "";
           return false;
       }
       if (min > num || max < num) {
           alert(num + ' n\'is not between ' + min + ' and ' + max);
           return false;
       }       
   } 
</script>

View the demo on jsFiddle.net.

Hopefully, this solution meets your needs.

Answer №2

By modifying the option you choose (yes or cancel), you have the ability to manipulate a confirm box.

If the maximum value is exceeded, you have the option to reset the value of a textbox by using

document.getElementById('value_one').value=0
.

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

Transform Promise-based code to use async/await

I'm attempting to rephrase this code using the async \ await syntax: public loadData(id: string): void { this.loadDataAsync() .then((data: any): void => { // Perform actions with data }) .catch((ex): v ...

Building on the Vuejs3 and Vuex4 framework, create a conditional rendering feature that triggers upon

I have a unique setup where custom objects are used to hold child objects full of data. The child objects start with null values for all properties, allowing them to be filled with data from remote sources when referenced. This results in a lazy-loading sy ...

The website must automatically adjust the size of all elements on the page, including images and fonts

I am currently facing an issue with the resizing of my web page when the user changes the window size or has a different screen resolution. I have created a jQuery function that triggers on resize or page load, which helps in scaling everything proportiona ...

Using express and sequelize to load different models in a single route

In my express application, I have successfully loaded related bus, family, and person models to supply them separately to the view. Now, I am trying to load the volunteerTypes model and pass it as a separate object to the view. exports.get = (request, res ...

Increasing several array elements within a MongoDB object

I have been struggling with this problem for some time now. My goal is to update multiple array values in the same object with a single query. The data in the database appears as follows: id: 616f5aca5f60da8bb5870e36 title: "title" recommendations: ...

Express.js does not recognize the req.query value

Incorporating Stripe Checkout functionality into a MERN application has been the focus of my recent project. Upon successful payment by a customer, they are directed to a checkout success URL where the CheckoutSuccess page is displayed. Additionally, Stri ...

Obtain image from an external server using AJAX

Our team is currently working on retrieving images from external servers that are cross-origin. While JSONP may not be effective in this case, we are exploring the use of plain AJAX GET requests. One potential workaround involves using iframes to manipulat ...

Issue with react-addons-css-transition-group and multiline TextFields in Material-UI TextField

If a TextField with multiline is nested inside a react-addons-css-transition-group, it seems to disrupt the show transition. Any suggestions on how to handle this situation effectively? Check out my code snippet here: https://codesandbox.io/s/material-dem ...

Identifying the initial object with a duplicate property within an array of objects using JavaScript

In my code, I have an array structured like this: var myArray = [ {id: 1, entry_id: 1, name: 'test', email: 'email1'}, {id: 2, entry_id: 1, name: 'test', email: 'email2'}, {id: 3, entry_id: 2, name: &ap ...

Conceal the Submit button upon completing the form submission using the load method

When creating a form and sending a request to another page, I use the following code: $(document).ready(function() { $("#send").click(function() { var text = $("#text").val(); var email = $("#email").val(); $("#exp").load("sendmail.php",{text: ...

I am attempting to assign a default value to a TextField by retrieving data from a GetMapping call in React, however, the value is not being successfully set

I am facing an issue with setting a default value for a TextField in my code. Even though I am trying to populate it with data from a GetMapping call, the value is not being set as expected. Here is the JSON response I receive from the API call: { "id": 1 ...

Combining and arranging numerous items in a precise location in three.js

I am currently working on a web application using three.js with Angular and facing some challenges when trying to set the precise positions of objects. The requirement is to load various objects and position them in specific locations. In order to load di ...

Tips for cutting down on bundle size in your WEBPACK setup when using VUEJS

I have tried numerous tutorials to reduce the size of my bundle, but none of them seem to be affecting the bundle size and I can't figure out why. Every time I integrate new code into webpack, the bundle size remains unchanged. (The application is c ...

attempting to merge two arrays into a single union

I am looking for a way to create a new array that contains only unique values from both the first and second arrays, maintaining their original order. This is my current approach: function union(first, second) { return first.filter(function(value) { ret ...

Transmitting data using JavaScript to Spring server

I am facing a challenge of uploading an image to a server using Spring. The code snippet I am using to get the file is as follows: var file = $("#form-field-photo").get(0).files[0]; I have attempted several methods to post it, but so far, all my attempts ...

Unable to retrieve dropdown value using JavaScript and display it in a div

javaScript code: Retrieving data from a dropdown and displaying it in the inner HTML of a div. function showcost() { var days = document.getElementById("Ddays"); var Dudays = days.options[days.selectedIndex].text; var div = docu ...

Clicking the download button will trigger the file to be downloaded every time

Within the documents table, I am iterating through metadata to extract a filename and docid which are then passed to my DocumentDownloadButton component: const DocumentsTableBody = ({ documentMetadata, tableProps }) => { const { Row, Data } = Table ...

Transmitting client-side Javascript data to backend server using Express

I am trying to fetch data from my frontend using the DOM and send it to the backend through Express but I'm unsure of how to proceed. I have used a POST method to console.log the data, but now I need help retrieving it in my Express backend. (The cons ...

Streamline the entire testing process of Google.Com by using Protractor to automate end-to-end testing

I need help with making Protractor navigate to google.com and search for a term. After successfully loading the non-angular page of Google, I am struggling to figure out how to make Protractor press "enter" or click the search button. Any suggestions? Ad ...

Unlock the potential of Vue custom props within the asyncData function in your nuxtjs project!

I have a special function in my project that serves as a plugin import Vue from 'vue' function duplicateText(text) { var input = document.createElement('input'); input.setAttribute('value', text); document.body.a ...