Random Snippets

  • Home
  • Sequence analysis blog
  • About
  • Categories
    • javascript
    • mysql
    • php
  • Subscribe via RSS

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.

Demo
green box

yellow box


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.

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.

Share with a friend:
    

Customize message


[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Comments or feedback...

If you have any demos that you would like to request, please do so.

Click to cancel reply

Recent Posts

  • Sorting 2D associative arrays in PHP
  • Dynamic or on-the-fly percentage calculations with JavaScript
  • The dangers of embedding the notorious “void(0)” JavaScript code in the href attribute of the “a” tag
  • How to randomly order or select rows in a MySQL query
  • How to convert MySQL timestamp to PHP date type

Recent Comments

  • Anders K on Simulate a button click via JavaScript
  • john on How to find and replace text dynamically via JavaScript
  • Eiolon on How to hide, show, or toggle your div
  • Use label as distant button in HTML – Community – travellin' meets real life on Simulate a button click via JavaScript
  • gaurav on Simulate a button click via JavaScript

Archives

Categories

  • javascript
  • mysql
  • php

©2010 Random Snippets