Wednesday, December 8, 2010

Ternary Operator?

The ternary operator is a shorthand for the classic if-else.  Its advantage is line-saving if you really enjoy writing compact code.

Form Submit Confirmation

Display a JavaScript OK/Cancel alert before submitting a form:

<form action="" method="post" onsubmit="return confirm('Are you sure you want to continue?')">

How it works...
  • onsubmit is an event that gets fired after the user hits a button of type image or submit, or if the user hits <Enter> from a text field. This event occurs before the form gets submitted to the action.
  • return funnels the user's boolean response to the form; true will continue with the form submission, false will prevent the form from submitting (cancel action)
  • confirm is a built-in JavaScript function to display an alert box with Yes/No-type responses. The argument is the string to be displayed in the alert.
Demo: