on
자바스크립트 - Form 폼 (양식) / 예제 (미완성)
자바스크립트 - Form 폼 (양식) / 예제 (미완성)
Insert title here function send() { var f = document.forms[0]; // elements : FORM 요소에 담긴 form 컨트롤(input, select, button, textarea 등) 배열 반환 for(var i=0; i - 일단 var f = document.forms[0]; 을 통해서 0번째 인덱스 즉 첫번째 폼을 f에 담고 - 폼이 담긴 f에서 여러 form 컨트롤 요소들을 찾는다. (비어있는 칸을 찾기 위해서) - form 요소들을 찾기위해서는 elements[i]를 사용해야하는데 이건 배열임 - for문으로 전체 요소 길이만큼 반복문 돌리고 for문 안에서 if문으로 확인을 거침 f.elements[i].value를 했을때 값이 있으면 true 없으면 false 반환 Insert title here function send() { var f = document.myForm; if(! f.name.value) { f.name.focus(); return; } if(! f.subject.value) { f.subject.focus(); return; } var s = f.name.value + "," + f.subject.value; alert(s); } form 접근 : 'document.폼이름' 으로 접근 이름 : 과목 : 등록하기 위랑 같은 개념이지만 폼에 접근하는 방식이 인덱스가 아니라 폼 이름으로 접근함 폼 이름으로 접근하는 방법이 더 안전하고 좋음 Insert title here submit 버튼 - 유효성 검사를 하지 않는 경우 이름 : 나이 : 전송하기 <%@ page contentType="text/html; charset=UTF-8"%> <% // 클라이언트가 서버로 보낸 정보의 문자 인코딩 request.setCharacterEncoding("utf-8"); // 클라이언트가 서버로 보낸 정보 받기 String name = request.getParameter("name"); int age = Integer.parseInt(request.getParameter("age")); String state = age >= 19 ? "성인" : "미성년자"; %> Insert title here 서버 - 결과 이름 : <%=name%> 나이 : <%=age%>, <%=state%> form 태그 중에서 button은 type을 따로 주지 않으면 기본적으로 submit 속성을 가진다. 그리고 이 submit 버튼은 image 버튼과 마찬가지로 => 서버로 전송이 가능한 버튼 타입이다. Insert title here function check() { var f = document.myForm; if(! f.name.value) { alert("이름을 입력 하세요"); f.name.focus(); return false; // 이벤트 취소 } if(! /^(\d)+$/.test(f.age.value)) { alert("나이는 숫자만 가능 합니다."); f.age.focus() event.preventDefault(); // 이벤트 취소 return; } return true; // 서버로 전송 // submit 버튼에서는 submit() 메소드를 호출하면 서버로 두번 전송되므로 절대로 호출해서는 안된다. // submit 버튼은 자바스크립트에 오류가 있는 경우 스크립트를 실행하지 않고 바로 서버로 전송하므로 주의해야 한다. } submit 버튼 - 유효성 검사 이름 : 나이 : 전송하기 서브밋 버튼은 조심해야 할 점이 많은데 서브밋 버튼을 누르면 서버로 전송이 일어나는데 만약 버튼에 메소드 호출까지 같이 달아놓으면 서버로 전송이 2번 되는것이고 또 자바스크립트에서 오류가 생기면 스크립트를 실행 안하고 그냥 바로 서버로 보내버린다. 그래서 submit 버튼을 쓸때는 주의를 해야하고, 서브밋 버튼을 눌렀을때 발생하는 서브밋 이벤트는 false를 반환 시키거나 event.preventDefault()를 호출해야지만 취소가 된다. Insert title here function check() { var f = document.myForm; if(! f.name.value) { alert("이름을 입력 하세요"); f.name.focus(); event.preventDefault(); // 이벤트 취소. // 이 예제는 return false; 로는 이벤트가 취소 되지 않음 return; } if(! /^(\d)+$/.test(f.age.value)) { alert("나이는 숫자만 가능 합니다."); f.age.focus() event.preventDefault(); return; } } // form에 submit 이벤트 등록 /* window.onload = function(){ document.myForm.addEventListener("submit", check); }; */ window.onload = () => document.myForm.addEventListener("submit", check); submit 버튼 - 유효성 검사 이름 : 나이 : 전송하기 여기서는 return false로는 취소를 못한다. form에 submit 이벤트를 창이 열리면 추가되게 해놨으므로 이벤트 제거 메소드를 호출 해야한다. Insert title here function send() { var f = document.myForm; if(! f.name.value) { alert("이름을 입력 하세요"); f.name.focus(); return; } if(! /^(\d)+$/.test(f.age.value)) { alert("나이는 숫자만 가능 합니다."); f.age.focus() return; } // submit 기능이 없는 컨트롤에서 서버로 전송할 경우 submit() 함수를 호출한다. f.submit(); // 서버로 전송 } 일반 버튼 - 서버로 전송 이름 : 나이 : 전송하기 이번에는 버튼에 submit 타입이 아니라 그냥 버튼 타입을 줬는데 자바스크립트에서 폼 자체를 submit() 함수로 보내 버릴 수 있다. Insert title here function send() { var f = document.myForm; var s = ""; if(! f.name.value ) { f.name.focus(); return; } if(! f.age.value ) { f.age.focus(); return; } s = " 이름:"+f.name.value+" 나이:"+f.age.value+" 좋아하는 과목:"; // 동일한 이름이 2개 이상이면 배열로 처리해야 한다. for(var i = 0; i 자바스크립트 코드에서 이름과 나이가 입력 안되면 코드 멈추고 text칸 활성화 하는 if문 2개가 있다. 그리고 변수 s가 이제 HTML 에 쏴줄 코드인데 좋아하는 과목 같은 경우 입력하는 text 박스는 3개나 있지만 이 text 박스들의 name 속성이 전부 subject로 똑같다. 이걸 자바스크립트에서 처리 해줘야 한다. subject의 총 길이를 가지고 인덱스를 나눠서 그걸 하나하나씩 반복문으로 뽑아서 s에 담아야한다. Insert title here window.onload = function(){ var f = document.myForm; // f.subject.value = "web"; // value 속성에 select 박스중 선택할 option의 value를 주면 선택됨 f.subject[3].selected = true; // subject[3] : subject에서 선택할 option의 위치 }; function send() { var f = document.myForm; var s = ""; if(! f.subject.value ) { alert("좋아하는 과목 선택은 필수입니다."); return; } s = " 이름:"+f.name.value+" 출신도:"+f.city.value+" 가장좋아하는과목:"+f.subject.value+" 취미:"; for(var i=0; i 그리고 보통 서버로 전송할때 value값을 주지만 만약 value값이 없으면 text가 서버로 전송 된다. 취미 부분보면 value 부분이 서버 전송 값이고 태그가 감싸고 있는 text가 눈에보이는 그냥 텍스트다 f.subject[3].selected = true; 이건 선택박스에서의 기본값을 설정하는거다. 인덱스로 3번째 위치를 기본으로 보여주겠다 라는 뜻 보통은 0번 인덱스로 할듯 f.subject.value = "web"; 이렇게 인덱스가 아니라 값으로 선택박스의 기본값을 설정도 가능 예제) Insert title here * { margin: 0; padding: 0; box-sizing: border-box; } body { font-size: 14px; font-family: "Malgun Gothic", "맑은 고딕", NanumGothic, 나눔고딕, 돋움, sans-serif; } a { color: #000; text-decoration: none; cursor: pointer; } a:active, a:hover { text-decoration: underline; color: #F28011; } .btn { color: #333; border: 1px solid #333; background-color: #fff; padding: 4px 10px; border-radius: 4px; font-weight: 500; cursor:pointer; font-size: 14px; font-family: "맑은 고딕", 나눔고딕, 돋움, sans-serif; vertical-align: baseline; } .btn:hover, .btn:active, .btn:focus { background-color: #e6e6e6; border-color: #adadad; color:#333; } .boxTF { border: 1px solid #999; padding: 5px 5px; background-color: #fff; border-radius: 4px; font-family: "맑은 고딕", 나눔고딕, 돋움, sans-serif; vertical-align: baseline; } .selectField { border: 1px solid #999; padding: 4px 5px; border-radius: 4px; font-family: "맑은 고딕", 나눔고딕, 돋움, sans-serif; vertical-align: baseline; } .board { margin: 30px auto; width: 700px; } .title { width:100%; font-size: 16px; font-weight: bold; padding: 13px 0; } .table { width: 100%; border-spacing: 0; border-collapse: collapse; } .table th, .table td { padding: 10px 0; } .table-border tr { border-bottom: 1px solid #ccc; } .table-border thead tr:first-child { border-top: 2px solid #ccc; } .table-list thead tr:first-child{ background: #eee; } .table-list td { text-align: center; } .table-list td:nth-child(6n+3) { text-align: left; padding-left: 5px; } .table-list tbody tr:hover { background: #efffef; } .table-list .chk { width: 40px; color: #787878; } .table-list .num { width: 60px; color: #787878; } .table-list .subject { color: #787878; } .table-list .name { width: 100px; color: #787878; } .table-list .date { width: 100px; color: #787878; } .table-list .hit { width: 70px; color: #787878; } .paginate { clear: both; text-align: center; white-space: nowrap; font-size: 14px; } .paginate a { border: 1px solid #ccc; color: #000; font-weight: 600; text-decoration: none; padding: 3px 7px; margin-left: 3px; vertical-align: middle; } .paginate a:hover, .paginate a:active { color: #6771ff; } .paginate span { border: 1px solid #e28d8d; color: #000; font-weight: 600; padding: 3px 7px; margin-left: 3px; vertical-align: middle; } .paginate :first-child { margin-left: 0; } function check() { var f = document.listForm; // checkbox 이름이 nums 인 요소가 한개도 없는 경우 if( f.nums === undefined ) { // if(! f.nums) { return; } // checkbox 이름이 nums 인 요소가 한개인 경우 if( f.nums.length === undefined ) { // if(! f.nums.length) { f.nums.checked = f.chkAll.checked; return; } // checkbox 이름이 nums 인 요소가 두개 이상인 경우 // 동일한 이름의 요소가 두개 이상인 경우에만 length 속성이 존재한다. // checked 속성 : checkbox, radio 버튼을 선택/해제하거나 선택 유무를 true/false로 반환 for(var i = 0; i < f.nums.length; i++) { f.nums[i].checked = f.chkAll.checked; } } function deleteList() { var f = document.listForm; var cnt = 0; if( ! f.nums ) { return; } if( f.nums.length ) { // nums가 여러개인 경우 for(var i=0; i 게시판 기능 중 일부인 체크박스 체크 기능하고 / 체크박스 선택 유무에 따라 삭제 메세지 기능만 있음. 먼저 check() 메소드는 체크박스의 개수 유무에 따른 체크를 하기 위해 만든다. 체크박스들의 name은 전부 nums임 체크박스가 하나도 체크 안되었을 경우 => 그냥 리턴 체크박스 하나만 체크 되었을 경우(length로 구분 length는 0개 1개까지는 false) => 체크된 된 요소가 하나일 경우니까 그냥 전체 체크박스 클릭하면 얘가 클릭하게 함. 체크박스가 2개이상 체크 되었을 경우 => length로 for문 돌려서 다 체크 시켜주기. 리스트 기능은 여기서는 서버로 보내는 기능은 없으니까 그냥 cnt로 개수만 세준다. cnt가 0일 경우는 삭제할 게시물을 하나도 선택 안한거고 여러개나 하나일 경우는 if문 하나로 해결이 가능하다. Insert title here *{ margin: 0; padding: 0; box-sizing: border-box; } body { font-size: 14px; font-family: "맑은 고딕", 나눔고딕, 돋움, sans-serif; } a { color: #000; text-decoration: none; cursor: pointer; } a:active, a:hover { text-decoration: underline; color: #F28011; } .btn { color: #333; border: 1px solid #333; background-color: #fff; padding: 4px 10px; border-radius: 4px; font-weight: 500; cursor:pointer; font-size: 14px; font-family: "맑은 고딕", 나눔고딕, 돋움, sans-serif; vertical-align: baseline; /* 부모 요소의 기준선에 맞춤 */ } .btn:hover, .btn:active, .btn:focus { background-color: #e6e6e6; border-color: #adadad; color:#333; } .boxTF { border: 1px solid #999; padding: 5px 5px; background-color: #fff; border-radius: 4px; font-family: "맑은 고딕", 나눔고딕, 돋움, sans-serif; vertical-align: baseline; } .selectField { border: 1px solid #999; padding: 4px 5px; border-radius: 4px; font-family: "맑은 고딕", 나눔고딕, 돋움, sans-serif; vertical-align: baseline; } textarea:focus, input:focus { outline: none; } .member { width: 600px; margin: 30px auto 25px; } .title { width:100%; font-size: 16px; font-weight: bold; padding: 13px 0; } .table { width: 100%; border-spacing: 0; border-collapse: collapse; } .table th, .table td { padding: 7px 0; } .table-border tr { border-bottom: 1px solid #ccc; } .table-border tr:first-child { border-top: 2px solid #ccc; } .table-form tr td:first-child{ background: #e6e6e6; text-align: center; width: 120px; } .table-form tr td:nth-child(2) { text-align: left; padding-left: 10px; } .table-form input[type=text]:focus, .table-form input[type=password]:focus { border: 1px solid tomato; } function isValidDateFormat(date) { if(date.length != 8 && date.length != 10) return false; var p = /(\.)|(\-)|(\/)/g; date = date.replace(p, ""); var format = /^[12][0-9]{7}$/; if(! format.test(date) ) return false; var y = parseInt( date.substr(0,4) ); var m = parseInt( date.substr(4,2) ); var d = parseInt( date.substr(6) ); if(m<1 || m>12) return false; var lastDay = (new Date(y,m,0)).getDate(); if(d<1 || d>lastDay) return false; return true; } function memberOk() { var f = document.memberForm; var s; // 아이디는 5~10자 이며 영문자로 시작하고 영숫자와_로 구성 if(! /^[a-zA-Z]\w{4,9}$/.test(f.userId.value)) { alert("아이디는 영문자로 시작하며, 5~10자이내의 영숫자로 구성합니다.") f.userId.focus(); return; } // 패스워드는 5~10자이며 영문자와 하나이상의 숫자 또는 특수문자를 포함해야함 s = f.userPwd.value if(! /^(?=.*[a-z])(?=.*[!@#$%^&*-=+]|.*[0-9]).{5,10}$/i.test(s)) { alert("패스워드는 5~10자이내로 영문자와 숫자 또는 특수문자로 구성합니다.") f.userPwd.focus(); return; } if(s != f.userPwd1.value) { alert("패스워드가 일치하지 않습니다."); f.userPwd.focus(); return; } // 이름은 한글 2~5자 이내이거나 영어 이름 : 이름(2~20) 성(2~20) // 이름은 한글 2~5자 이내 s = f.userName.value; if(! /^[가-힣]{2,5}$/.test(s)) { alert("이름을 입력하세요"); f.userName.focus(); return; } // 생년월일 if(! isValidDateFormat(f.birth.value) ) { alert("생년월일을 입력하세요"); f.birth.focus(); return; } if(! f.email1.value.trim() ) { alert("이메일을 입력하세요"); f.email1.focus(); return; } if(! f.email2.value.trim() ) { alert("이메일을 입력하세요"); f.email2.focus(); return; } if(! f.tel1.value ) { alert("전화번호 입력하세요"); f.tel1.focus(); return; } if(! /^\d{3,4}$/.test(f.tel2.value) ) { alert("전화번호 입력하세요"); f.tel2.focus(); return; } if(! /^\d{4}$/.test(f.tel3.value) ) { alert("전화번호 입력하세요"); f.tel3.focus(); return; } alert("회원 가입 성공 ^^"); } function changeEmail() { var f = document.memberForm; var s = f.selectEmail.value; if(s === "direct") { f.email2.value = ""; f.email2.readOnly = false; f.email1.focus(); } else { f.email2.value = s; f.email2.readOnly = true; f.email1.focus(); } } | 회원 가입 아 이 디 패스워드 패스워드 확인 이 름 생년월일 이 메 일 선 택 네이버 메일 한 메일 핫 메일 지 메일 직접입력 @ 전화번호 선 택 010 02 031 032 033 041 042 043 044 051 052 053 054 055 061 062 063 064 070 - 우편번호 우편번호검색 주 소 직 업 회원가입 다시입력 가입취소 Insert title here * { margin: 0; padding: 0; box-sizing: border-box; } body { font-size: 14px; font-family: "맑은 고딕", 나눔고딕, 돋움, sans-serif; } a { color: #000; text-decoration: none; cursor: pointer; } a:active, a:hover { text-decoration: underline; color: #F28011; } .btn { color: #333; border: 1px solid #333; background-color: #fff; padding: 4px 10px; border-radius: 4px; font-weight: 500; cursor:pointer; font-size: 14px; font-family: "맑은 고딕", 나눔고딕, 돋움, sans-serif; vertical-align: baseline; } .btn:hover, .btn:active, .btn:focus { background-color: #e6e6e6; border-color: #adadad; color:#333; } .boxTF { border: 1px solid #999; padding: 5px 5px; background-color: #fff; border-radius: 4px; font-family: "맑은 고딕", 나눔고딕, 돋움, sans-serif; vertical-align: baseline; } .selectField { border: 1px solid #999; padding: 4px 5px; border-radius: 4px; font-family: "맑은 고딕", 나눔고딕, 돋움, sans-serif; vertical-align: baseline; } .boxTA { border:1px solid #999; height:150px; padding:3px 5px; border-radius:4px; background-color:#fff; resize : none; vertical-align: baseline; } textarea:focus, input:focus { outline: none; } .title { width:100%; font-size: 16px; font-weight: bold; padding: 13px 0; } .container { width: 400px; margin: 30px auto; } .table { width: 100%; border-spacing: 0; border-collapse: collapse; } .table th, .table td { padding: 7px 0; } .table-border tr { border-bottom: 1px solid #ccc; } .table-border tr:first-child { border-top: 2px solid #ccc; } function itemAdd() { var f = document.noteForm; var item = f.itemLeft; // select 요쇼에 option 요소 추가 item[item.length] = new Option("김자바", "kim"); // text, value item[item.length] = new Option("스프링", "spring"); item[item.length] = new Option("서블릿", "servlet"); item[item.length] = new Option("오라클", "oracle"); item[item.length] = new Option("이자바", "lee"); item[item.length] = new Option("홍자바", "hong"); item[item.length] = new Option("나대한", "na"); } window.onload = () => itemAdd(); // 선택된 option을 좌 또는 우로 이동 function itemMove(pos) { var f = document.noteForm; var source, target; if(pos==="left") { // right -> left source = f.itemRight; target = f.itemLeft; } else { // left -> right source = f.itemLeft; target = f.itemRight; } var len = source.length; for(var i=0; i 미완성 게시글 from http://heidong.tistory.com/122 by ccl(A) rewrite - 2021-10-06 02:27:45