스프링에서 게시판을 공부하며, form 에 입력된 데이터를 컨트롤러에 전송 하기 전에

유효성 검사를 하고 싶었지만, form 내부에 있는 input태그의 submit 타입은,

클릭 하면 바로 전송이 되서 유효성 검사를 진행 할 수 없었습니다.


그때, submit 타입을 button 타입으로 바꿔주시고

클릭 이벤트 발생시 form 을 submit 해주면 됩니다.


	

		$("#form1").on("click", function() {
			var title = $("#title").val();
			var startedDate = $("#startedDate").val();
			
			if(title==""){
				alert("Write the Title");
				$("#title").focus();
			} else if(startedDate==""){
				alert("Select the Started Date");
				$("#startedDate").focus();
			}
			
			document.getElementById("postForm").submit();	// 유효성 검사 후 submit
		});

Ajax 전송 때문에 거의 몇 일 동안 프로젝트 진행을 못 했는데

알고보니 제가 엉뚱하게 사용하고 있었네요 ㅠㅠ

Ajax의 이론을 자세히 모르시는 분은 꼭 먼저 이론을 이해 하시는걸 추천합니다.


간단하게,

ajax 메소드 안의 url 은 요청이 전송될 위치이며, type은 필요 방식에 설정 하시면 됩니다.

data 또한 전송할 데이터들을 선언 해주시면 되구요,


error, success, complete 는 예외처리라고 생각하실 수 있겠지만,

success 는 정상 처리 되었을때, complete는 finally 같은 구문이고,

error야 말로 예외처리라 할 수 있습니다.


$.ajax({ url : "전송할 URL", type : "POST", data : { title : title, startedDate:startedDate, finishedDate : finishedDate, summary : summary }, dataType : "json", error : function(error) { alert("error 발생"); }, success : function(data) { alert("전송 성공"); }, complete : function() { alert("최종 성공"); } });


브라우저 객체(BOM)의 객체인 screen 객체 메소드에 이은,

location객체와 history 객체의 메소드 입니다.



location.href : URL을 설정 및 반환 합니다.

location.host : URL 호스트 이름과 포트 번호를 설정 및 반환합니다.

location.hostname : URL의 호스트 이름을 설정 및 반환합니다.

location.hash : URL의 해쉬값을 설정 및 반환합니다.

location.origin : URL의 프로토콜, 호스트이름, 포트번호를 반환합니다.

location.protocol : URL의 프로토콜을 설정 및 반환합니다.

location.port : URL의 포트 번호를 설정 및 반환합니다.

location.search : URL의 쿼리스트링을 설정 및 반환합니다.

location.reload() : 화면을 새로고침 합니다.(F5와 같은 기능)


history.length : 방문 목록 갯수를 표현합니다.

history.back() : 이전 페이지로 이동 합니다.

history.forward() : 존재하는 다음 페이지로 이동 합니다.

history.go() : 인덱스 값에 맞춰 페이지가 이동 합니다.


navigator.appCodeName : 브라우저 이름을 반환합니다.

navigator.appName : 브라우저 이름을 반환합니다.

navigator.appVersion : 브라우저의 버전 정보를 반환합니다.

navigator.cookieEnabled : 쿠키 사용 여부를 반환합니다.

navigator.geolocation : 유저 접속 위치의 Geolocation 객체를 반환합니다.

navigator.language : 브라우저의 사용 언어를 반환합니다.

navigator.onLine : 온라인 브라우저 인지 확인합니다.

navigator.platform : 운영체제 정보를 반환합니다.

navigator.product : 브라우저 엔진 이름을 반환합니다.

navigator.userAgent : 서버 정보를 반환합니다.

navigator.javaEnabled() : 자바 사용 여부를 확인 합니다.(boolean)



결과 값이 보이는 내용만 테스트 하였습니다.





	console.log(navigator.appCodeName);
	console.log(navigator.appName);
	console.log(navigator.appVersion);
	console.log(navigator.cookieEnabled);
	console.log(navigator.geolocation);
	console.log(navigator.language);
	console.log(navigator.onLine);
	console.log(navigator.platform);
	console.log(navigator.product);
	console.log(navigator.userAgent);
	console.log(navigator.javaEnabled());





실행 결과 :





자바스크립트의 배열을 추가,  삭제, 정렬 기능을 사용할 수 있는

배열 메소드를 코딩 하였습니다.


join('문자열') : 배열 객체 데이터를 문자열로 이어줍니다.

reverse() : 배열 객체 데이터의 정렬 순서를 역방향으로 해줍니다.

slice(index1, index2) : index1 ~ index2 까지의 구간을 잘라서 표현합니다.

sort() : 배열 객체 데이터를 오름차순으로 정렬합니다.

concat(배열) : 선택된 배열+'배열'을 하나의 배열로 연결 합니다.

pop() : 배열 객체 데이터의 마지막 데이터를 삭제합니다.

push() : 마지막 인덱스에 새로운 데이터를 추가 합니다.

shift() : 배열 객체 데이터의 맨 첫번째 데이터를 삭제 합니다.

unshift() : 첫번째 인덱스 앞에 새로운 데이터를 추가 합니다.



	var arr1 = ['A', 'B', 'C', 'D'];
	var arr2 = ['가', '나', '다', '라'];
	var arr3 = [1, 5, 3, 8, 2, 7];
	var arr4 = ['E', 'F', 'G', 'H'];
	var arr5 = ['a', 'b', 'c', 'd'];

	console.log(arr1.join(' & '));	// join('문자열')
	console.log(arr1.reverse());	// reverse()
	console.log(arr3.slice(0,3));	// slice(index1, index2)
	console.log(arr3.sort());		// sort()
	console.log(arr3.splice());		// splice()
	console.log(arr4.concat(arr5));	// concat(array)
	arr2.pop();		// pop()
	arr2.push('카카');	// push('문자열')
	arr2.shift();		// shift()
	arr2.unshift("가가"); // unshift('문자열')
	console.log(arr4.length);	




결과 : 






단순하게 날짜 (연/월/일)을 받아 현재 날짜 기준 디데이를 계산하는 코드입니다.


today는 Date() 객체를 이용한 오늘 날짜를 계산하는 변수이고,

stdDate는 입력받은 날짜를 Date()객체로 저장하는 변수입니다.


stdDate의 월에 -1을 해준 이유는, 

1~12월이 1~12가 아니라 0~11이기 때문입니다.






	var today = new Date();

	var inYear = prompt("년도 입력");
	var inMonth = prompt("월 입력");
	var inDate = prompt("일 입력");
	
	var stdDate = new Date(inYear,(inMonth-1),inDate);
	var gapDate = stdDate.getTime() - today.getTime();
	
	var gapDay = Math.ceil(gapDate / (60*1000*60*24));
	
	if(gapDay<0) {
		gapDay = -gapDay;
		console.log(gapDay+"일 지났습니다.")	
	} else if(gapDay>0) {
		console.log(gapDay+"일 남았습니다.");
	} else if(gapDay==0) {
		console.log("당일 입니다.");
	}






결과 :



홈페이지 개발시 날짜 및 시간을 출력하는 소스입니다. 

자바스크립트 내장객체중 Date 객체를 사용 하였습니다.


Date 객체의 getDay() 메소드는 현재 요일을 0(일)~6(토) 까지의 숫자로 표시 해줍니다.

그래서 switch 문을 이용하여 요일로 수정 하였습니다.


	var dt = new Date();
	var year = dt.getFullYear(); // 년도
	var month = dt.getMonth();	 // 월
	var date = dt.getDate();	 // 일
	var day = dt.getDay();		 // 요일(포맷 전)
	var hours = dt.getHours();	 // 시간
	var mins = dt.getMinutes();	 // 분
	var snd = dt.getSeconds();	 //초
	var msnd = dt.getMilliseconds(); // 밀리초
	
	console.log(day);
	var dayName;	// 요일(포맷 후)
	
	switch(day) {
		case 0:dayName="일요일"; break;
		case 1:dayName="월요일"; break;
		case 2:dayName="화요일"; break;
		case 3:dayName="수요일"; break;
		case 4:dayName="목요일"; break;
		case 5:dayName="금요일"; break;
		case 6:dayName="토요일"; break;
	}
	
	document.write(year+"년 "+month+"월 ",+date+"일 "+dayName+"
"); document.write(hours+"시 "+mins+"분 "+snd+":"+msnd+"초");





출력 결과 : 




페이지가 로드될때 넘어 오는 매개변수로 select박스의 selected를 설정하고 싶었습니다.


eq(인덱스) 와 attr()속성을 이용하니 쉽게 설정 할 수 있었어요!


아래 설렉터에 위치한 내용은, postType이란 id를 참조 하고 그 자식인 option을 더 참조 합니다.

eq(인덱스)를 이용하여 상세 설정 하고 싶은 부분을 입력 하면 됩니다.

그리고 attr 메소드를 이용하여 선택된 option에 'sealected' , 'selected'를 추가 해줍니다.


$("#postType option:eq(0)").attr('selected', 'selected');


이 내용을 html 코드로 하면 이렇습니다.





$(document).ready(function() {
       var test = "firstType"

	if(test =="firstType") {
		$("#postType option:eq(0)").attr('selected', 'selected');
	} else if(test =="secondType") {
		$("#postType option:eq(1)").attr('selected', 'selected');
	} else if(test =="thirdType") {
		$("#postType option:eq(2)").attr('selected', 'selected');
	}
});


<input type="text"/> 박스를 이용하여 

1번 박스에서 2번 박스로 value값을 전송하는 방법입니다.

제이쿼리의 val() 메소드는 해당 영역에 있는 value 값을 불러 올 수 있습니다.

그 이후 document.getElementById("txtBoxId").value 에 해당 val() 값을 넣어주면 됩니다.


html 태그

         


javascript&Jquery

        function test01() {
                 document.getElementById("txtBox2").value = $("#txtBox1").val();
	}


+ Recent posts