Searching Body Text with textRange: Building on the Script and the VBScript Alternative - Add a Flag
(Page 2 of 4 )
Fortunately, this is fairly easy. All you need to do is add a flag to the first function that is set when that function is called (when the find button is clicked.) If the second button is clicked and that flag has not been set, you can produce an alert that tells the user to click the find button first and enter a search term, thus preventing the error. First add another global variable to the top of the page:
var button1clicked
Now, in the first function (textSearch), set the flag to 1 at the beginning of the function:
button1clicked = 1
This tells the script that the find button has definitely been clicked. Now a simple if statement at the top of the second function to test the value of the flag variable quickly lets the script accordingly if the first button has not been clicked:
if (button1clicked != 1) {
window.alert ("Please enter a search value first");
return false
}
Like we added an if statement in the first article to ensure that the page did not error when no value was passed back to a variable that was expecting one, this statement simply checks that button1clicked does equal 1, but if not, alerts the user.
Finally, if a user clicks the x button at the top of the dialog box instead of clicking the cancel button an alert informs the user that ‘undefined’ couldn’t be found, which is rather silly as undefined was not entered as a search term. This happens because in this case, as when the user searches for a word that is not found in the body text, match does equal false and the appropriate alert is fired. It would be better all round if nothing happened when the x button was clicked, just like when the cancel button is clicked. Change the first if statement in the first function to this:
if (searchWord=="") {
return false
} else if (searchWord==null) {
return false
}
Now test it. If you search for a word that is not present in the text, you still get the "couldn’t find ‘word’" message, and if you click the x button or the cancel button on the search dialog, nothing happens and no errors occur. Similarly, the second if statement of the second function can also be modified in the same way so that if a user opens the search dialog window (thus setting button1clicked to 1) but then closes it without entering a search word and then clicks the find next button, an error message more appropriate is displayed:
if (searchWord=="") {
window.alert ("No Search value entered");
return false
} else if (searchWord==null) {
window.alert("No search value entered");
return false
}
The script should now be able to handle anything a user throws at it.
Next: The VBScript >>
More Code Examples Articles
More By Dan Wellman