빈 문자열("")과 NULL을 활용한 조건문으로 값이 비어 있는지 간단히 확인할 수 있습니다. 이 방법을 사용하면 사용자가 텍스트 상자에 값을 입력하지 않고 폼을 제출할 때 경고 메시지를 표시하도록 처리할 수 있습니다.
예제 코드
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<form name="register" onsubmit="return checkingUserName()">
USERNAME: <input type="text" name="username">
<input type="submit" value="Save">
</form>
<script>
function checkingUserName() {
var username = document.forms["register"]["username"].value;
if (username == null || username == "") {
alert("Please enter the username. Can't be blank or empty !!!");
return false;
}
}
</script>
</body>
</html>위 프로그램을 실행하려면 파일 이름을 "anyName.html(index.html)"로 저장한 뒤 해당 파일을 마우스 오른쪽 버튼으로 클릭하세요. 그다음 VS Code 편집기에서 "Open with Live Server" 옵션을 선택하면 브라우저에서 바로 결과를 확인할 수 있습니다.
실행 결과
위 코드를 실행하면 다음과 같은 화면이 출력됩니다.

Save(저장) 버튼을 클릭하면 사용자 이름이 비어 있을 경우 아래와 같은 경고창과 함께 메시지가 표시됩니다.
