Extracting information from a text field and checking which button was selected, either "yes" or "

Currently, I am exploring JavaScript examples on w3schools and I have a question. Is there a way to retrieve the text entered by the user while also determining if the user clicked OK or Cancel?

I understand how to check if OK or Cancel was selected:

var r=confirm("Press a button");
 if (r==true)
   {
   alert("You pressed OK!");
   }
 else
   {
   alert("You pressed Cancel!");
   }

And I know how to obtain data from a text field:

var name=prompt("Please enter your name","Harry Potter");
if (name!=null && name!="")
  {
  document.write("<p>Hello " + name + "! How are you today?</p>");
  }

However, is there a way to capture both of these inputs simultaneously?

Thank you

Answer №1

let userAge;
userAge = prompt('Please enter your age:','');

if (userAge == null) {
    alert('User clicked Cancel.');
}
else {
    alert('User clicked OK.');
}

If the user clicks cancel or closes the dialog box, the variable userAge will be assigned a value of null.

Answer №2

let userName = prompt("What is your name?", "John Doe");
if (userName == null)
    alert("User Canceled");
else if (userName == "")
    alert("Okay, but you didn't enter anything");
else
    alert("Hello, "+ userName + "! Welcome.");

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

Prevent automatic merging of JSON data with identical IDs

My AJAX call to a PHP select request is as follows: $.ajax({ type: "POST", url: "/renforts/_getIntervenantManager", data: { IDMission : IDMission, IDManager : IDManager }, dataType : 'json' ...

Ways to separate the strings in angular JS

I'm looking to divide a string into two parts. For instance: www.example.com/page.html?abcdef123456 I want to split the above URL string and save the part that comes after the question mark (?) into a variable. Can anyone advise on how to accomplis ...

Optimal strategies for initializing Knockout JS models from backend code

Upon taking over a website that utilizes knockout js and asp.net, I noticed some performance issues during the initial page load. After investigating, I found that there are approximately 20 models on the site, each making an ajax call to retrieve data fro ...

What could be the reason for the appearance of this error message: 'Illegal arguments: undefined, string'?

Currently, I am in the process of developing a node.js application where I have created a backend API specifically for user registration. However, when testing it using Postman, I encountered an error message stating 'Illegal arguments: undefined, str ...

Development of a custom waterfall toolbar design using MUI framework

I've been working with a setup similar to the one found here: https://codesandbox.io/s/1op5mqq9oq By clicking on the checkboxes, the <Toolbar /> is displayed. As you scroll down the page, the <Toolbar /> remains fixed at the top and even ...

Server-side issue: Ajax POST request returns an empty POST array

I've encountered an issue with my JavaScript function that is supposed to collect data and send it to a PHP file. My problem lies in attempting to submit an array as part of the post: Here's the snippet of the function in question: var string ...

Exploring the functionalities of Stripe's latest Search API integrated with metadata features

I'm currently working on a project to showcase products stored in the Stripe Database. I attempted to implement this using if statements, filters, and the new Search API of Stripe, but unfortunately, my attempts were unsuccessful. Any ideas on what el ...

Implementing user-driven filtering in a React table

When a user clicks on the submit button, data will be loaded. If no filter is applied, all data will be displayed. const submit = async (e: SyntheticEvent) => { e.preventDefault(); const param = { ...(certificateNo && ...

"Enhance Your Highchart Experience by Adding Hyperlinks to Every Segment of Your Stacked Bar

I am seeking to assign a specific link to each segment of a stacked 100% bar chart. Check out this demo of a stacked bar chart: http://www.highcharts.com/demo/bar-stacked Here's what I am trying to accomplish: Please visit , input data in the left t ...

Using separate files for routes in Express.js can help organize and streamline your code

I'm facing an issue while setting up a node project where I need to organize my files. Specifically, I want to place a file routes.js within the routes/routes.js directory and controllers files in the controllers/ directory. For instance, let's ...

Implementing validation and displaying fields with v-model in vue.js

Looking at this code snippet: <button type="button @click="editing=true">Edit</button> <form v-show="editing" @submit="onSubmit"> <textarea v-model="text"></textarea> </form> <div> Current value: {{text}} </ ...

Organizing and managing one-on-one table tennis matches using a customized data structure. Leveraging the power of Vue, JavaScript, and

Seeking advice on the best approach for storing table tennis match data in a web application. I currently have a method in place that works, but I'm open to suggestions for improvement. Here is my current idea: matches: [ { id: 1 datePlayed ...

Does Leaflet.js provide a method to cycle through all markers currently on the map?

Is there a way to make my map icons scale in size with zoom instead of being a static 38x38? If CSS can achieve this, I'm open to that option as well. It seems like it would also involve iterating through all markers, but I haven't been able to f ...

Ways to transfer data between Angular controller and jQuery

Looking for some guidance on how to toggle between two HTML divs based on user input validation using an Angular controller and jQuery animations. Each div contains input fields that need to be validated before moving on to the next stage. Here is a simpli ...

Achieving JSON element sorting in the most effective way

https://i.stack.imgur.com/NQbdN.png Each array contains the following information: {{ id: 39, treaty_number: "qwe", insurant_name: "222", belonging_to_the_holding_company: "test", date_start: "2016-04-15", etc }} Is there a way to sort each array in asc ...

The navigation links in my React project are not appearing on the screen as expected

Hello everyone, I am relatively new to React and recently I have been attempting to utilize `react-router` in order to construct a Single Page Application. My goal is to link all the pages (such as Home, About, Login, etc) in the navigation bar using the & ...

What is the best way to continuously execute the 'onclick' function using AJAX inside a specific ID?

My challenge involves implementing a new AJAX upload feature to insert a data element from the onClick event in multiple rows. The issue I am facing is that it works fine for the first row, but when I add subsequent rows, the function no longer works upon ...

Exploring the Power of Pythons, Selenium, and XPATH for Handling New Windows

Is it possible to retrieve an element through XPath after using the .click() method when that element is located within a section of JavaScript known as BODY_BLOCK_JQUERY_REFLOW and appears only after the click action? I am attempting to access this speci ...

Tips for adding content to several elements at once using jQuery

My HTML structure is as follows : <span class="section2 section4">hello</span> <span class="section1">World</span> <div class="tab" id="tab1"></div> <div class="tab" id="tab2"></div> <div class="tab" id= ...

Issues encountered with certain Tailwind styles functioning improperly when deployed in a production environment with Next.js

It seems that there are some style issues occurring in the production build hosted on Netlify for a specific component. The problematic component is a wrapper located at ./layout/FormLayout.tsx. Below is the code for this wrapper: const FormLayout: React.F ...