You can put alerts anywhere you need to monitor a value, but what if your application is freezing up? If there is a syntax error in your code and your browser error messages aren't any help, use comments to exclude certain parts of your code from executing.
In this case we will comment out everything that is within the body of the function and insert an alert to monitor the value being sent to the function.
If you had panicked and jumped into the middle of your code, especially if it was more complex than the above example, you may have been tearing your hair out (not an option for us older folk) for hours trying to figure this one out.
Now correct the mistake and then try clicking the button again after reloading the page. You should see an alert that shows you the name of the text field "myField."
Now select the comment characters "/*" and move them to just before the if construct and move the alert line to the line below the first line in the function code and change the argument, as below.
When you run the script by clicking the button you should get an alert that displays the object string for a text box. However, we are using a document method getElementsByName("name"). This method isn't quite like document.getElementById() in that it returns a collection of objects that have the name for which you are looking. You need to use the item() function to retrieve the correct object from the collection. In this case we only have one with the name "myField." Not all browsers currently support or completely implement document.getElementsByName("name"). Implementation problems such as this are commonplace in Web development. If you are just starting out, then believe me, you have many of these wonderful problems (bugs if you will) to live through.
Please note that the "name" attribute for HTML tags is supposed to be depreciated for any further versions of HTML in favor of the "id" attribute. Unfortunately, many browsers will not send data from form controls to the server that do not have a name attribute set. Use both id and name, the document.forms collection, or pass this .form.nameOfTargetObject (nameOfTargetObject being the name of whatever form control you are trying to address in your script) to your scripts when working with form controls.
We now have a name and id attribute for "myField" which allows us to use the more convenient and well supported document.getElementById(). We can now move to the "if" construct inside our function. Move both sets of comment characters "/*" and "*/"and move the alert inside the if block as shown below.
Why is there no alert? That's because we are checking to see if the form field is blank (empty string). Since we have an initial value of "Hello" for our form field, the if construct will not evaluate to true and the code inside the if block will not execute. If that is what you intended, cool, we can move on; otherwise change "==" in the if statement to "!=" which means not equal to.