본문 바로가기

공부/JS , HTML , CSS

[javascript] table tr 복사(clone()), tr의 td삭제하기, 버튼 클릭 시 테이블 합치기(rowspan), 삭제버튼, class 이름바꿔서 추가하기

완성된 화면

 

 

 

 

 

클릭해서 실행해 보세요

- 옵션추가 : 옵션 목록 추가

- 항목추가 : 옵션칸의 크기 늘려 항목 줄 추가 (옵션 rowspan)

- 삭제 : 항목 삭제 (rowspan된 칸을 유지하면서 항목 줄만 삭제하기)

 

옵션명 항목명 필수항목 가격 재고 옵션추가
     

 

개발 순서

1) 옵션을 추가할 때마다 늘어나는 행이름을 다르게 하여 추가하였다

2) 항목을 추가할 때는 기존의 행과 이름이 같게 해주기 위해 기존 행을 기능을 포함해 복사clone(true)하고 복사된 행의 첫 번째 열을 삭제하였다

3) rowspanNum 함수는 옵션의 rowspan할 열 수를 지정해준다

 

html code

<body>
    <input type="button" name="addOpt" value="옵션추가">
    <table id="box">
        <thead>
            <th>옵션명</th>
            <th>항목명</th>
            <th>필수항목</th>
            <th>가격</th>
            <th>재고</th>
            <th>옵션추가</th>
        </thead>
        <tbody>
            <tr class="1rows">
                <td class="optionName"><input type="text"><input type="button" name="addPro[]" value="항목추가"></td>
                <td></td>
                <td><input type="checkbox"></td>
                <td></td>
                <td></td>
                <td><input type="button" name="del[]" value="삭제"></td>
            </tr>
        </tbody>
    </table>
</body>

 

javascript code

<script>
        $(function(){
            var newRow = $(".1rows").eq(0); // 첫 번째 행을 newRow라는 변수로 지정

            $("input[name=addOpt]").click(function() {
                $("#box tbody").append(newRow.clone(true)); //newRow의 요소뿐만 아니라 데이터, 기능까지 모두 복사 (버튼과 같은 기능 사용 위해)
                $("#box tr:last").attr('class',($(".optionName").length+'rows')); //tr 마다 다른 class 이름 부여
                $("#box tr:last").find("td:first").removeAttr("rowspan"); //첫 번째 열의 rowspan 값을 가지고 있다면 그대로 복사되기 때문에 rowspan 속성 삭제
            })

            $("input[name='del[]']").click(function() {
                var clickDel = $(this).parent().parent();
                clsName= clickDel.attr("class");

                //삭제 할 열이 항목추가 버튼을 가지고 있는 경우 항목추가 버튼을 다음 같은 class tr으로 넘기기
                if (clickDel.find("td:first").attr("class")=="optionName" && clickDel.attr("class")==clickDel.next().attr("class")) {
                    clickDel.next().prepend(clickDel.find("td:first").clone(true));
                    clickDel.remove();                    
                } else {
                    clickDel.remove();
                }

                rowspanNum(clsName); 
            })

            $("input[name='addPro[]']").click(function(){
                clickRow=$(this).parent().parent();
                clickRow.after(clickRow.clone(true)); //옵션명이 같은 항목끼리는 클래스 이름을 같게 하기 위해 클릭된 열 복사
                clickRow.next().find("td:first").remove();
                clsName= clickRow.attr("class");
                
                rowspanNum(clsName);
            })

            function rowspanNum(clsName) { //rowspan 값 설정
                rowspan= $('.'+clsName).length;
                $("."+clsName+":first").find("td:first").attr("rowspan",rowspan);
            }
        })

    </script>

 

 

 

전체 코드

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

    <title>Document</title>
    <style>
        table, tr{
            border: solid 1px;
            width: 90%;
        }

        td,th {
            border: solid 1px;
        }
    </style>

    <script>
        $(function(){
            var newRow = $(".1rows").eq(0);

            $("input[name=addOpt]").click(function() {
                $("#box tbody").append(newRow.clone(true));
                $("#box tr:last").attr('class',($(".optionName").length+'rows'));
                $("#box tr:last").find("td:first").removeAttr("rowspan");
            })

            $("input[name='del[]']").click(function() {
                var clickDel = $(this).parent().parent();
                clsName= clickDel.attr("class");

                if (clickDel.find("td:first").attr("class")=="optionName" && clickDel.attr("class")==clickDel.next().attr("class")) {
                    clickDel.next().prepend(clickDel.find("td:first").clone(true));
                    clickDel.remove();                    
                } else {
                    clickDel.remove();
                }
                
                rowspanNum(clsName);
            })

            $("input[name='addPro[]']").click(function(){
                clickRow=$(this).parent().parent();
                clickRow.after(clickRow.clone(true));
                clickRow.next().find("td:first").remove();
                clsName= clickRow.attr("class");
                
                rowspanNum(clsName);
            })

            function rowspanNum(clsName) {
                rowspan= $('.'+clsName).length;
                $("."+clsName+":first").find("td:first").attr("rowspan",rowspan);
            }
        })

    </script>
</head>
<body>
    <input type="button" name="addOpt" value="옵션추가">
    <table id="box">
        <thead>
            <th>옵션명</th>
            <th>항목명</th>
            <th>필수항목</th>
            <th>가격</th>
            <th>재고</th>
            <th>옵션추가</th>
        </thead>
        <tbody>
            <tr class="1rows">
                <td class="optionName"><input type="text"><input type="button" name="addPro[]" value="항목추가"></td>
                <td></td>
                <td><input type="checkbox"></td>
                <td></td>
                <td></td>
                <td><input type="button" name="del[]" value="삭제"></td>
            </tr>
        </tbody>
    </table>
</body>
</html>