본문 바로가기

Programming/과거포스팅

jquery tr 아래위로 이동 (jquery tr up down)

코드에 대한 자세한 설명은 생략합니다. 체크가 되어있는 행을 위아래로 움직이는 소스입니다.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> TR UP DOWN </title>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
 <script type="text/javascript">
	$(document).ready(function() {
		$('#down').click(function(){
			var checkedCount = $("input[name=id]:checked").length;
			if (checkedCount > 1 ) {
				alert("이동하려는 행을 하나만 선택해주세요")
			} 
			else if(checkedCount == 0) {
				alert("이동 하려는 행을 선택해주세요")
			}
			else {
				var element = $("input[name=id]:checked").parent().parent();
				moveRowDown(element)
			}
    	});
		
		$('#up').click(function(){
			var checkedCount = $("input[name=id]:checked").length;
			if (checkedCount > 1 ) {
				alert("이동하려는 행을 하나만 선택해주세요")
			} 
			else if(checkedCount == 0) {
				alert("이동하려는 행을 선택해주세요")
			}
			else {
				var element = $("input[name=id]:checked").parent().parent();
				moveRowUp(element)
			}
    	});
	});

	var moveRowUp = function(element) {
		if( element.prev().html() != null  && element.prev().attr("id") != "header"){
			element.insertBefore(element.prev());
			changNum();
		} else {
			alert("최상단입니다.")
		}
	};
	
	var moveRowDown = function(element) {
		if( element.next().html() != null ){
			element.insertAfter(element.next());
			changNum();
		}  else {
			alert("최하단입니다.")
		}
	};
	
	var changNum = function() {
		var num = 0;
		$('input[name=platform_num]').each(function(){
			num++;
			$(this).val(num);
		});
	};
</script>
</head>
<body>
<div style="height: 500px; width: 100%; overflow-y: auto;">
<form name="delForm" method="post">
	<table width="100%">
		<colgroup>
			<col width="33%">
			<col width="33%">
			<col width="33%">
		</colgroup>
		 <tr id="header">
		 	<th><input type="checkbox"></th>
			<th>순번</th>
<th>지역</th>  </tr> <tr align="center"> <td><input type="checkbox" name="id"></td> <td><input type="text" name="platform_num" value="1"></td> <td>시청</td> </tr> <tr align="center"> <td><input type="checkbox" name="id"></td> <td><input type="text" name="platform_num" value="2"></td> <td>군청</td> </tr> <tr align="center"> <td><input type="checkbox" name="id"></td> <td><input type="text" name="platform_num" value="3"></td> <td>동사무소</td> </tr> </table> </form> </div> <div align="right" style="margin-right: 20px"> <input type="button" id="up" value=""> <input type="button" id="down" value=""> </div> </body> </html> </body> </html>