I wish to validate a value when either the user leaves the field by using the tab key or if they click on a button. I have defined an onchange function to perform a validation if they change the field then change it and also an onmousedown function on the save button to perform validation then save the value. The user may click on the save button to save the value rather than tab out of the field.
I originally had an onchange and an onclick but the onclick never fired if they clicked on the button.
If you enter an invalid value, I have set the onchange to set a flag (valueValidated), so that the "Invalid Value" message is only displayed once. However, in saveValue, it seems that valueValidated has not been set as it still has a value of false even if it has veen set in checkValue.
I split the example into two files as my original code is split into two files just so it matches the original code. Why does the code not work correctly?
Note: I know that IE6 performs the onmousedown before the onchange and I have been able to change my original code so it works with IE6.
eventTest.html
Expand|Select|Wrap|Line Numbers
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title></title>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <script type="text/javascript" src="eventTest.js"></script>
- </head>
- <body>
- <label>Enter a value between 1 and 10</label>
- <input id="number" onchange="checkValue(this)" />
- <button onmousedown="saveValue()">Save Value</button>
- </body>
- </html>
Expand|Select|Wrap|Line Numbers
- // Indicates if the value has been through the validation process not whether the value is correct
- var valueValidated = false;
- function numberInRange (number)
- {
- var numberValid = true;
- if (1 > number || 10 < number)
- {
- numberValid = false;
- }
- return numberValid;
- }
- function checkValue(numberObj)
- {
- // Original checkValue performs additional operations so we can't put it into numberInRange
- var numberValid = numberInRange (numberObj.value);
- if (false == numberValid)
- {
- valueValidated = true;
- alert ("Number out of range (checkValue), valueValidated = " + valueValidated);
- }
- }
- function saveValue ()
- {
- var numberValid = false;
- if (false == valueValidated)
- {
- var numberObj = document.getElementById ("number");
- numberValid = numberInRange (numberObj.value);
- if (false == numberValid)
- {
- alert ("Number out of range (saveValue), valueValidated = " + valueValidated);
- }
- }
- if (false == numberValid)
- {
- valueValidated = false; // Force re-validation if user clicks on Save button again.
- alert ("Save aborted, valueValidated = " + valueValidated);
- }
- }