jQuery로 테이블 tr 동적으로 추가,삭제 하기 v2 > script

본문 바로가기
사이트 내 전체검색

script

jQuery로 테이블 tr 동적으로 추가,삭제 하기 v2

페이지 정보

작성자 서방님 댓글 0건 조회 184회 작성일 13-12-06 16:16

본문

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=euc-kr">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
 // 옵션추가 버튼 클릭시
 $("#addItemBtn").click(function() {
  // item 의 최대번호 구하기
  var lastItemNo = $("#example tr:last").attr("class").replace("item", "");
  var newitem = $("#example tr:eq(1)").clone();
  newitem.removeClass();
  newitem.find("td:eq(0)").attr("rowspan", "1");
  newitem.addClass("item"+(parseInt(lastItemNo)+1));
  $("#example").append(newitem);
 });

 // 항목추가 버튼 클릭시
 $(".addBtn").live("click", function() {
  var clickedRow = $(this).parent().parent();
  var cls = clickedRow.attr("class");
  // tr 복사해서 마지막에 추가
  var newrow = clickedRow.clone();
  newrow.find("td:eq(0)").remove();
  newrow.insertAfter($("#example ."+cls+":last"));
  // rowspan 조정
  resizeRowspan(cls);
 });

 // 삭제버튼 클릭시
 $(".delBtn").live("click", function() {
  var clickedRow = $(this).parent().parent();
  var cls = clickedRow.attr("class");

  // 각 항목의 첫번째 row를 삭제한 경우 다음 row에 td 하나를 추가해 준다.
  if( clickedRow.find("td:eq(0)").attr("rowspan") ){
  if( clickedRow.next().hasClass(cls) ){

  clickedRow.next().prepend(clickedRow.find("td:eq(0)"));
  }
  }
  clickedRow.remove();
  // rowspan 조정
  resizeRowspan(cls);
 });

 // cls : rowspan 을 조정할 class ex) item1, item2, ...
 function resizeRowspan(cls){
  var rowspan = $("."+cls).length;
  $("."+cls+":first td:eq(0)").attr("rowspan", rowspan);
 }
});
</script>
</head>
<body>
<button id="addItemBtn">옵션추가</button>
<table id="example" border="1px">
 <tr>
  <th>옵션명</th>
  <th>항목명</th>
  <th>필수항목</th>
  <th>가격</th>
  <th>재고</th>
  <th>옵션추가</th>
 </tr>
 <tr class="item1">
  <td><input type="text" /><button class="addBtn">항목추가</button></td>
  <td><input type="text" /></td>
  <td><input type="checkbox" /></td>
  <td><input type="text" /></td>
  <td><input type="text" /></td>
  <td><button class="delBtn">삭제</button></td>
 </tr>
</table>
</body>
</html>


댓글목록

등록된 댓글이 없습니다.

Total 846건 7 페이지
게시물 검색

회원로그인

접속자집계

오늘
77
어제
84
최대
1,347
전체
154,448
Latest Crypto Fear & Greed Index

그누보드5
Copyright © 서방님.kr All rights reserved.