mercredi 24 juillet 2013

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

Aucun commentaire:

Enregistrer un commentaire