How to confirm or prompt user for input via JavaScript


JavaScript has a built-in function called confirm which takes a string argument that poses the question to the user and gives them the option to click the OK or Cancel buttons and returns true if the user clicks OK.

Demo
green box

yellow box



Here is the HTML code:

  1. <div id="parentDiv" style="background-color: green;padding:10px;">
    
  2.     green box
    
  3.     <div id="yellowBox" style="background-color: yellow;padding:10px;">
    
  4.         yellow box
    
  5.     </div>
    
  6. </div>
    
  7. <input type="button" value="Remove the yellow box" onClick="var answer = confirm('Are you sure you want to remove the yellow box?'); if (answer) { removeYellowBox(); }">

The magic is in line 7 where we use confirm to ask a user if he or she really wants to delete our yellow box and retrieves the returned value and saves it in the answer variable. We then test if the answer variable is true and, if so, execute the removeYellowBox function.

In addition to the confirm function, JavaScript also has another built-in function called prompt which prompts the user for input.

Demo

Here is the HTML:

  1. <input type="button" value="prompt user" onClick="var answer = prompt('What is your favorite OS?', 'OSX'); alert('You said ' + answer + '!');"

The prompt function will take 2 arguments: the string text for the user to see in the dialog box and the default value for the input. It also returns the user’s input which we have nicely saved into our answer variable.

Published by

Allen Liu

Building websites is a passion of mine. During the course of my work, I have created some snippets of code that I hope will prove useful to other developers.

Leave a Reply

Your email address will not be published. Required fields are marked *