How to confirm or prompt user for input via JavaScript
June 26th, 2008 | Published in 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.
Here is the HTML code:
1 2 3 4 5 6 7 | <div id="parentDiv" style="background-color: green;padding:10px;">
green box
<div id="yellowBox" style="background-color: yellow;padding:10px;">
yellow box
</div>
</div>
<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.
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.
Share with a friend:Customize message