|
|
|
Text fields are the perfect objects to get a small amount of input into your web application from the user, for example a phone number. JavaScript can query the data in a specified text field and check it to ensure it's the information the application expects.
The following example is going to require the user to type a number in the text field once the number is typed the user is expected to press the "check number" button. The "onclick" event of this button will call the "check number " function which will get a reference to the text field, check if it's value is a number and finally show the value with a message stating wether it's a number or not. Run Code | View Code
<form name="myForm">
Define the text field
<input type="text">
Give the text field a name
<input type="text"
name=" myTextField ">
Define the button
<input type="button">
Set the text on the button's face
<input type="button"
value="Check number">
Register the onClick event
<input type="button" value="Check number"
onclick="">
Make the onClick event call the "checkNumber" function
<input type="button" value="Check number" onclick="
checkNumber ()">
Close the form
</form>
This function first declares two local variables being "value" and "message". "value" will be assigned the value of the text field and "message" will be assigned one of two messages depending on the "value" variable.
For this function to continue it must get the value from the text field. It does this by first referring to the document object then the document object refers to the (predefined) form object "myForm" the form then refers to the (predefined) text field "myTextField". Once the text field is reference it's value is then inserted into "value" variable by referencing it's value property.
After the value property is set into the "value" variable it is checked to see if it's not a number with the "isNaN" (Is Not A Number - top-level JavaScript function). When nothing is typed into the text field "isNaN" thinks it is a number. However I disagree and believe a value of nothing is not a number so the code then checks if nothing was typed into the text field. If either of these conditions are met the "message" variable is set to the value of the "value" variable with a hard coded string stating that it is NOT a number. If the conditions fail the message variable is then again set to the value of "value" but this time with a hard coded string stating it is a number. Finally the alert method is used to show the formatted message.
function checkNumber (){
var value
var message
Make the value variable the same value of the text field's value
useing the document tree.
value = document.myForm.textField.value
Check if the value is Not a number or if it is an empty string
if(isNaN(value) || value == "" ){
message = "The value[" + value + "] is NOT a number"
}else{
message = "The value [" + value + "] is a number"
}
Show a model dialog with the message
alert(message)
}
See also Checkbox | Radio button | Select