Java Reference
In-Depth Information
</script>
</body>
</html>
Save this as ch14 _ question2.html .
In the HTML, notice that the links for checking the username and e‐mail address are gone. There is
no need for them, because those values are checked when the user clicks the Submit button. The last
statement of the JavaScript code registers that event listener:
document.getElementById("btnSubmit")
.addEventListener("click", btnSubmitClick);
The function that handles the button's click event is called btnSubmitClick() . It's a simple function
that kicks off the whole process:
function btnSubmitClick(e) {
e.preventDefault();
checkUsername();
}
Its first statement prevents the form from submitting. This is important because, due to the nature
of asynchronous processes, btnSubmitClick() cannot be responsible for submitting the form.
Therefore, another function will need to submit the form if both the username and e‐mail address
validate and are available.
The second statement calls checkUsername() , which is left mostly unchanged:
function checkUsername() {
var userValue = document.getElementById("username").value;
if (!userValue) {
alert("Please enter a user name to check!");
return;
}
var url = "ch14_formvalidator.php?username=" + userValue;
var request = new HttpRequest(url, handleUsernameResponse);
request.send();
}
In fact, the only change to this function is the callback passed to the HttpRequest constructor. It's a
new callback function called handleUsernameResponse() , and it somewhat resembles the original
handleResponse() function:
function handleUsernameResponse(responseText) {
var response = JSON.parse(responseText);
if (!response.available) {
alert("The username " + response.searchTerm +
" is unavailable. Try another.");
Search WWH ::




Custom Search