웹 프로그래밍/JavaScript
[JS] DOM : form 태그 응용, 조건에 따른 submit 활용(onsubmit)
산을넘는다
2020. 6. 22. 11:32
아래와 같이 onsubmit에 return false 라고 쓰면, submit 버튼을 눌러도 action이 가리키는 곳으로 이동하지 않는다.
onsubmit 형태
onsubmit = "return false"
onsubmit = "return true"
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="http://www.naver.com" name="" onsubmit="return false">
<select>
<option>선택하세요</option>
<option>제목</option>
<option>작성자</option>
</select>
<input type="text">
<input type="submit" value="검색">
</form>
</body>
</html>
어떤 조건에 따라 이동할 것인지, 이동하지 않을 것인지 선택할 수 있게 구현해보자(onsubmit을 응용).
1. select 내에 option을 '제목' 또는 '작성자'를 선택하지 않으면, action으로 이동하지 않게 해보자.
2. input 태그 내에 text 타입에 내용을 작성하지 않으면, action으로 이동하지 않게 해보자.
// if(f.searchType.selectedIndex == 0) {
// if(f.searchType[0].selected){ // 위와 같은 의미다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
function checkForm() {
let f = document.searchForm
// if(f.searchType.selectedIndex == 0) {
if(f.searchType[0].selected){ // 위와 같은 의미다.
alert('검색항목을 선택하세요')
return false
}
if(f.searchWord.value == "") {
alert('검색어를 입력하세요')
return false
}
return true
}
</script>
</head>
<body>
<form action="http://www.naver.com" name="searchForm" onsubmit="return checkForm()">
<select name="searchType">
<option>선택하세요</option>
<option>제목</option>
<option>작성자</option>
</select>
<input type="text" name="searchWord">
<input type="submit" value="검색">
</form>
</body>
</html>
추가 조건
3. 선택하지 않은 항목에 focus 기능을 넣어보자. (검은색 테두리 효과)
4. 내용을 2글자 이상 작성하지 않으면 action으로 이동하지 않게 해보자.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
function checkForm() {
let f = document.searchForm
// if(f.searchType.selectedIndex == 0) {
if(f.searchType[0].selected){ // 위와 같은 의미다.
alert('검색항목을 선택하세요')
f.searchType.focus()
return false
}
/*
if(f.searchWord.value == "") {
alert('검색어를 입력하세요')
return false
}
*/
/*
if(f.searchWord.value == ''){
let keyword = ''
switch(f.searchType.selectedIndex){
case 1:
keyword = '제목'
break
case 2:
keyword = '작성'
break
}
alert('검색 할 ' + keyword + '을/를 입력하세요.')
}
*/
let words = ['', '제목', '작성자']
if(f.searchWord.value == ''){
alert('검색할 ' + words[f.searchType.selectedIndex] + "을(를) 입력하세요")
f.searchWord.focus()
return false
}
if(f.searchWord.value.length < 2) {
alert('검색어는 2글자이상 입력하세요')
f.searchWord.focus()
return false
}
return true
}
</script>
</head>
<body>
<form action="http://www.naver.com" name="searchForm" onsubmit="return checkForm()">
<select name="searchType">
<option>선택하세요</option>
<option>제목</option>
<option>작성자</option>
</select>
<input type="text" name="searchWord">
<input type="submit" value="검색">
</form>
</body>
</html>