mercredi 24 juillet 2013

JavaScript Confirm box

JavaScript Confirm is also a type of a popup box. It is used to ask user to confirm a certain requested action. If user confirms it, the browser proceeds and performs that action.

For example you ask the Browser to delete a picture from your facebook profile. A confirm box will pop up asking you to confirm the action "Are you sure to delete the file?", You can proceed by pressing OK Button or Cancel if you mistakently pressed the delete button or just changed your mind.
Syntax

confirm("message");
Example 1

In the example below, we are displaying a warning message to the user. If she chooses ok, she will be redirected to the main page, however she can also choose to click cancel.

We can later add more functionality to the script below using the If statement, to redirect those who click 'OK' to the site's main page, while do not load the page for those who choose to cancel. However since this lesson is part of Javascript basics, we only explain the basic use of confirm box here. We will deal with the IF part in later lessons on Conditional statements.

javascript confirm box

In the example above, we put a Button on a simple web page. Besides we defined a function in the head section of the page, and named it jsconfirm. This function will launch the confirm box whenever it is called.

We also programmed the button to call the function jsconfirm whenever the button is pressed(the button press event captured using Onclick event handler).
You can Copy Paste the code below into a new html file.

<html>
<head>
<title>JS Confirm Box</title>

<script type="text/javascript">
function jsconfirm()
{
confirm("Warning! The Content of this site may be disturbing to some viewers" + '\n' + "Viewer Discretion Is Advised");
}
</script>
</head>

<body>
<p>Click Here to Enter the site</p>

<input type="button" onclick="jsconfirm()" value="Enter Site" />
</body>
</html>
Result

When the button is pressed, the popup box will appear.

js confirm

NOTE: After you press ok, nothing will happen, because as mentioned above, in this example we are not telling the browser about what to do with the input taken.

PopUp Box Message Line Break '\n'

If the message is too lengthy, it will be put into the next line, however we can also enter a line break '\n' to manually enter a line break in the popup window message as in the example above.
JavaScript Confirm and the Boolean Values (Advance topic)

This part of the lesson explains a slightly advanced topic and also makes use of the conditional statements. If you are taking this course step by step from the beginning, you can skip this part and maybe later refer to it after we have covered the conditional statements.

In JavaScript a confirm OK pressed is equal to a boolean 1 or 'TRUE' and a confirm Cancel is equal to a boolean 'False'.
Example

In the example below, we will use the Confirm command as a condition in a Conditional statement. So if OK is pressed it will mean that the condition has been met OR is true.

js confirm code

We did not mention any event with the confirm command, so the confirm box will pop up with page load.

Javascript confirm conditional

If the condition is true, i.e. OK has been pressed in the confirm popup box, it will execute the command in the brackets. It will pop up an alert

js confirm boolean true

If the condition is False, i.e. Cancel has been pressed in the confirm popup box, it will execute the command in the brackets after the ELSE. It will pop up a different alert as specified in the code.

js confirm boolean false

JavaScript Prompt box /Window

JavaScript Prompt is also a type of a popup box. It is used to ask(prompt) user for certain input, which then javascript uses for certain operations and decision making. For example, ask visitor to enter age, before she can be allowed to enter a site which is restricted for those under 13. Syntax prompt ("message", "default value"); Example 1 In the example below, we are prompting the visitor to enter her age. We can later add more functionality to the script below using the If statement, to redirect those above 13 to the site's main page, while deny entrance to those under 13. However since this lesson is part of Javascript basics, we only explain the use of the prompt box to take input, what we later do with that input, is a part of later lessons. js prompt In the example above, we put a Button on a simple web page. Besides we defined a function in the head section of the page, and named it jsprompt. This function will launch the JS Prompt box whenever it is called. We also programmed the button to call the function jsprompt whenever the button is pressed(the button press event captured using Onclick event handler). You can Copy Paste the code below into a new html file. JS PopUp Boxes

Clicking the Button below will launch an alert box.

Result When the button is pressed, the popup box will appear. Here we chose the click button event to launch the box, we can also program to launch the prompt box on any other event, like simple page load. javascript prompt window NOTE: After you press ok, nothing will happen, because as mentioned above, in this example we are not telling the browser about what to do with the input taken. Example 2- Making use of the input value In this example, we will use a simple code to work with the input taken. prompt user 1. We defined a function called jsprompt2. This function not only makes use of the prompt command to ask for input, but will also assign the input value to a variable called visitorname. 2. Then the function will display the customized welcome message on the screen with the value of the variable we named visitorname(the value user entered in the prompt). 3. We placed a button on the page and programmed it to call the function jsprompt whenever the button is pressed(the button press event captured using onclick). Result When Ok is pressed. prompt result NOTE: In this example, we also mentioned a default Value for the prompt box input, so when the box pops up, by default the value 'Visitor' is already there. User can click in the box and enter her own name however. You can Copy Paste the code below into a new html file. JS Prompt Box

Plz Click the Button and enter your name

Example 3- Another example of the JavaScript PopUp box making use of Loops is presented at a later lesson at- JavaScript For Loops

JavaScript Alerts PopUp Box

Alert is a way of passing on some information to the page user/visitor OR simply it alerts the user about a certain event. Event like Page load, button click, form submit, clicked inside a field etc. See JavaScript Events for more.

The Alert command launches a PopUp box containing some text message for the visitor. The user is required to acknowledge the receipt of information usually by pressing a 'OK' button that appears in the box.
Syntax

Alert ("message");

Example

javascript alert box

In the example above, we put a Button on a simple web page. Besides we defined a function in the head section of the page, and named it js_alert. This function will launch the alert box whenever it is called.

We also programmed the button to call the function js_alert whenever the button is pressed(the button press event captured using Onclick event handler).
You can Copy Paste the code below into a new html file.

<html>
<head>
<title>JS PopUp Boxes</title>
<script type="text/javascript">

function js_alert()
{
alert("This is your first alert box");
}

</script>
</head>

<body>
<p>Clicking the Button below will launch an alert box.</p>

<input type="button" onclick="js_alert()" value="Launch Alert Box" />

</body>
</html>


Result

alert box in chrome

Note that the alert box appears as a separate small size window in Chrome browser.

JavaScript PopUp Boxes / Windows

What is a PopUp Box/ window?

A PopUp box is a small message box window that appears(pops up) in your browser in response to a certain Event like Page load, button click, form submit, clicked inside a field etc. See JavaScript Events for more.

The main types of Javascript popup boxes

    Alert Box- Give some info to user
    Prompt Box - Ask user to input some value like name, age etc.
    Confirm Box- Confirm before proceeding with a request ex- delete a file.

Popup boxes appear differently in different browsers.
PopUp Box as it appears in FireFox

In Mozilla Firefox 5.0, the JavaScript Popup box appears in the center of page. But unlike IE and Chrome, the box does not appear as a separate movable window. you cannot click and drag it across the screen.

JS popup box firefox
JS PopUp Box Appears in Internet Explorer 8

You can click and hold down the mouse key as shown in the screenshot below and drag the popup window across the screen.

javascript popus in internet explorer

Note the Yellow symbol, that is an IE 8 symbol for Alerts.

JavaScript PopUp Box / Window Appears in Google Chrome

alert box in chrome
PopUp Boxes Sytntax

We will deal with practical examples of popup windows in the next lesson, however the general syntax is

command name ("text message");
PopUp Box Message Line Break

If the message is too lengthy, it will be put into the next line, however we can also enter a line break '\n' to manually enter a line break in the popup window message. Example in Lesson on JS Confirm box

Syntax- Defining Function in Javascript

There are certain elements that need to be defined for a function to work.
Syntax

function nameoffunction (var1, var2 ...........)
{
Code to be executed
}
Lets look at each of those parts

    First comes the reserve word 'function' .this is to tell the interpreter/browser that we are defining a function and the following code is part of this function. NOTE : If you recall lessons on basics- javascript is a case sensitive language, so writing it Function or FUNCTION will cause errors.
    Give the function a name ex. 'myresults' or any other suitable name that also gives some meaning to the purpose of the function i.e. the task it performs.
    Variables- values of these variables are generally provided by the user on the page where function is called.
    Curly Braces { } to mark the start and end of the executable code.
    Code- Instructions on what to do with those variable values and how to display the results.

Example- JS Function

Functions are used in a variety of places in the website, most commonly with JS events. We will study events in detail in later lessons. First, lets look at a simpler example.

Step 1- Declare the function

We declared a function and named it 'contact'. This contains our lenghty contact info, we wish to display it multiple times on our page. NOTE- the example is to explain the concept to you in simple terms.(Real world application- you wish to display the info at end of every page- function kept in external JS file

declaring a Javascript function

    We declared a funciton in the head section of the page and named it 'contact'.
    No variables were required for this simple operation, so the ( ) are empty.
    In the Curly Braces, we wrote instructions on what to do when the function is called by its name from anywhere in the page.
    Where the function is called, javascript write a message on screen.

Step 2- Call the Function

Call the function by its name where it is required.

calling javascript function

    We wished to call the function in the body tag, where we wanted it to display the contact info.
    Then we called the function again, no repitition of the lenghty message.

Result

function result


Example 2- Defining Function and using with Events

This is the most common use of functions. The function is called to execute its code, when a certain event occurs. Like when you click the buttons in the example below, it will display a JS Confirm message.

Step 1- Declare the function

declare function

    We declared a funciton in the head section of the page and named it 'welcome'.
    No variables were required for this simple operation, so the ( ) are empty.
    In the Curly Braces, we wrote instructions on what to do when the function is called by its name from anywhere in the page.
    When the function is called, javascript should popup a 'Confirm Box' displaying a particular message.

Step 2- Call the Function

Call the function by its name where it is required.



js calling function

    We created some form buttons within the body and associated a mouse event with them.
    Whenever these buttons are clicked (JS onclick event), browser should run the function called 'welcome'.

Note- in the example above, we have used the function thrice while the code is written in the head section of the page only once. This saves repitition and enforces consistency.

What is a Function in JS ?

A function is a block of code that performs a certain specialized task. The benefit is that instead of writing that code over and over again on every web page it is needed, you can simply refer to that block of code(function) and instruct it to perform the task.

For example- sometimes you need to count the number of spaces in paragraphs, and programming is needed to calculate that. There are three ways to achieve this objective

Method # 1 -Write the coding yourself and paste the whole code, everywhere it is required. Lot of repitition.

Method # 2- Write the coding yourself, give that block of code a name and place it in a separate file. Now on any page it is required, call it by its name to perform the required task.

Method # 3- If available, Use a predefined function, those created by others or come pre-loaded with the programming language or software. Have you Noticed the 'Word Count' feature in Microsoft Word? every time you use that, at the backend a function is called.

You will come across many pre built functions in JS and other programming languages. For examples, string functions for calculating lenght of a word.

Example of a mathematical function-A Mathematical Function for calculating power of a number. 8 ^ 3 is the simple instruction you will give, at the backend code will be 8 x 8 x 8 and there will be instructions in the function on how to display result on screen. like instead of simple dispalying result 512, it can be programmed to output 'The answer to your question is 512 my liege!"
Basic Function Types

    Built-in Functions- preloaded in javascript interpreters, you don't need to define them.
    User defined functions- Ones you can specify by encapsulating some code in a block and giving that block a name.

Our main focus in this chapter will be Custom/User defined Functions

JavaScript OnClick Event

This event handler is used to instruct the browser on What action to take when a certain object is clicked.

If the concept of events is new to you, it is recommened that you first see lesson on What are Javascript events
Syntax

onclick="functionname( )"

The name of function that has to be called when this event occurs.
NOTE: Simple Js code can also be written here instead of calling function, but standard practice with events is to use them with functions.

Step 1- Declare the function

declare function

    We declared a funciton in the head section of the page and named it 'welcome'.
    No variables were required for this simple operation, so the ( ) are empty.
    In the Curly Braces, we wrote instructions on what to do when the function is called by its name from anywhere in the page.
    When the function is called, javascript should popup a 'Confirm Box' displaying a particular message.

Step 2- Call the Function

Call the function by its name where it is required.



js calling function

    We created some form buttons within the body and associated a mouse OnClick event with them.
    Whenever these buttons are clicked, browser will detect the event and run the function called 'welcome'.