How to Test If a Property Has a Value in JavaScript
Each element on your Web page has properties. Properties are a part of the object that establishes design layout details such as the element's color, size, font or location on the page. You can use JavaScript to retrieve property values; however, these values will be blank if you did not set them when creating the Web page. Therefore, to test if a property has a value in JavaScript, check if the value is blank.
Instructions
-
-
1
Right-click your HTML file and select "Open With." Double-click "Notepad" to open a text editor. If you have a more advanced editor, you can choose it instead. The coding is the same regardless of your editor.
-
2
Create a JavaScript block. The JavaScript block is placed within the "<head>" and "</head>" tags. Type the following code in your HTML file:
<script language="Javascript"> </script>
All the following code is placed between these two tags.
-
-
3
Retrieve your element's property value. For instance, assume that the "value" property is the text located in a text box. If you want to detect if a text box has some kind of text entered into the "value" property, use code similar to the following:
var TestVar = form.first_name.value;
This code retrieves the value from a form element named "first_name." It's saved in a variable named "TestVar."
-
4
Determine if the property is set. For instance, if you want to display an alert dialog box if the user has not entered any text, you detect if the "value" property for the text box is set. Using the example "first_name" text box from Step 3, the following code only prints the alert dialog box if the property has no value:
if (TestVar == '' )
{
alert ("Please enter a first name.");
}
-
1