Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Modify the code of Listing 9.1 to also validate that the phone field of the form

ID: 3875088 • Letter: M

Question

Modify the code of Listing 9.1 to also validate that the phone field of the form is not blank. Have the program produce only one alert message, saying which field(s) require attention.

<!DOCTYPE html>
<html>
<head>
<title> Canceling Default Behavior </title>
<script>
function checkform() {
document.getElementById("form1").onsubmit = function() {
var allowSubmit = true;
if( document.getElementById("user").value == "") {
alert(" Name field cannot be blank ");
allowSubmit = false;
}
if(allowSubmit) alert(" Data OK - submitting form ");
return allowSubmit;
}
}
window.onload = checkform;
<script>
</head>
<body>
<form id ="form1">
Name: <input type ="text" value ="" name =" username" id =" user"/> [Required field]
<br/>
Phone: <input type =" text" value ="" name ="telephone" id ="phone"/> [Optional field]
<br/>
<input type =" submit"/>
</form>
</body>
</html>

Explanation / Answer

Solution

<!DOCTYPE html>
<html>
<head>
<title> Canceling Default Behavior </title>
<script>
function checkform() {
document.getElementById("form1").onsubmit = function() {
var allowSubmit = true;

if( document.getElementById("user").value == "" || document.getElementById("phone").value == "") {
if( document.getElementById("user").value == "") {
alert(" Name field cannot be blank ");

user.focus();
allowSubmit = false;
}

if( document.getElementById("phone").value == "") {
alert(" Phone field cannot be blank ");

phone.focus();
allowSubmit = false;
}
}

if(allowSubmit) alert(" Data OK - submitting form ");

return allowSubmit;
}
}
window.onload = checkform;
<script>
</head>
<body>
<form id ="form1">
Name: <input type ="text" value ="" name =" username" id =" user"/> [Required field]
<br/>
Phone: <input type =" text" value ="" name ="telephone" id ="phone"/> [Optional field]
<br/>
<input type =" submit"/>
</form>
</body>
</html>

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote