Javascript Alert
The Javascript alert method is very easy to use.
<script type="text/javascript">
alert('Hey man!');
</script>
This will pop-up an alert box that rather emphatically states "Hey man!"
If our script had a variable in it, we could pass that variable into our alert method like so:
<script type="text/javascript">
ko="Hey, Dog!";
alert(ko);
</script>
Notice that when we pass a variable to a method, we don't want any quotation marks or the variable will be read literally and will simply print the word
ko to the alert box... try it. alert('ko');
To go a little further, we'll pass a variable from an HTML text field to the alert function. The explanation is actually more complicated than the code.
First, the form:
<form name=mfo>
<input type=text name=mte onKeyUp="javascript:sayHey(mfo.mte.value)">
</form>
Then the script where we create our function:
<script type="text/javascript">
v=0;
function sayHey(ji) {
if (ji == "loves it" && v == 0) {
v=1;
alert(ji);
}
}
</script>
NOTE: When you put this script on your HTML page, you'll need to type "loves it" in the textfield to see the script do its thing.
-We built an
HTML form and named the form
mfo... just because.
-We made a text field and named it
mte... another random name.
-We invoked Javascript's built-in onKeyUp event handler.
-We called our
sayHey function every time a key on the keyboard goes up.
-We
passed what is in the field when the key goes up to our
sayHey function. This is represented in the
mfo.mte.value - In English, the
mfo form, the
mte field, the
value of that.
-That value is received in our function as
ji because
ji is a good name.
-We said
if ji equals "loves it" and
v equals zero, change
v to 1 and...
Call the
Javascript alert method and fire up
ji
NOTES:
The
v==0; part is to make sure our alert method is only called once. The first time our alert pops up, we change
v to 1 so we know our alert won't happen again. See, if our user hits the
return or enter key to say OK to the alert, the onKeyUp is invoked every time and the alert box keeps popping up. Although this doesn't happen in Internet Explorer, it does on Firefox, Safari, etc. Another reason it's good to test your code on different browsers.
More resources for Javascript alert can be found after the code below.
Free Copy and Paste Javascript Code:
<script type="text/javascript">
alert('Hey man!');
v=0;
function sayHey(ji) {
if (ji == "loves it" && v == 0) {
v=1;
alert(ji);
}
}
</script>
<form name=mfo>
<input type=text name=mte onKeyUp="javascript:sayHey(mfo.mte.value)">
</form>
Resources:
Alert Documentation at Sun microsystems
Opening an Alert Box in Javascript
HTML Tutorials
Javascript Function
Javascript Pass Variable
Javascript If
Javascript Alert Example
Click HERE to comment or discuss at iLoveTheCode GOOGLE Group