728x90

테이블에서 체크박스를 전체 선택/해제 그리고 체크박스 선택된 것만 특정 액션을 취하도록 하고 싶은 경우가 있다.

이걸 고려한 HTML5 및 JQuery 를 작성해봤다.

프로그램은 테스트를 통해서 몸으로 느끼고 내것으로 만들어야만 하는 작업이라는 걸 계속 체험하고 있다.



전체선택 박스 만들기

<th class="header" width="30"><input type="checkbox" id="checkall" /></th>



선택삭제 박스 만들기

<td colspan="5" style="text-align:left;"><span class="btnbox1">선택삭제</span></td>


.btnbox1 {
    background-color:#BFD7E9;
    border: none;
    padding: 10px 10px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 12px;
    margin: 4px 2px;
    cursor: pointer;
    }


체크 박스 나오게하는 테이블 만들기

=== boardClass.php 파일의 일부 ===

// column 개수, 게시물 총개수 만큼 자동으로 화면 출력
function tablelistView_checkbox($result){
    global $DB_CONNECT;
    if(is_object($DB_CONNECT)  && get_class($DB_CONNECT)=='mysqli'){
        while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
            $view='<tr class="tr1">';
            foreach($row as $column => $value) {
                if($column== 'uid'){
                    $view.='<td><input type="checkbox" class="chkbox" name="uid[]" value="'.$value.'" /></td>';
                }
                $view.='<td class="td2">'.$value.'</td>';
            }
            $view.='</tr>';
            echo $view;
        }
    } else {
        while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
            $view='<tr class="tr1">';
            foreach($row as $column => $value) {
                if($column== 'uid'){
                    $view.='<td><input type="checkbox" class="chkbox" name="uid[]" value="'.$value.'" /></td>';
                }
                $view.='<td class="td2">'.$value.'</td>';
            }
            $view.='</tr>';
            echo $view;
        }
    }
}


==== display.js ====

$(function(){
    // class td1 중에서 짝수번째 요소만 선택해서 배경색을 지정색으로 표시
    $(".tr1:odd").css("background-color","#F4F9FF");

    $('.tr1').click(function() {
        var idx=$(this).attr('id');
    }).mouseover(function() {
        $(this).children('.td2').css({'backgroundColor':'#DCDCDC','cursor':'pointer'});
    }).mouseout(function() {
        $(this).children('.td2').css({'backgroundColor':'#FFFFFF','cursor':'default'});
    });

    // 전체 선택, 전체 해제
    $("#checkall").change(function () {
        $("input:checkbox").prop('checked', $(this).prop("checked"));
    });

    $('.btnbox1').click(function(){
        var chkdata = new Array();
        // 헤더에 있는 체크박스는 제외
        //$('.chkbox:checked').each(function() {
        $('input:checkbox[name="uid[]"]:checked').each(function() {
            chkdata.push($(this).val());
            //alert($(this).val());
        });
        if(chkdata.length != 0){
            alert(chkdata);
            $.post('ajax.php',{chkdata:chkdata}, function(response) {
                alert(response);
            });
        } else {
            alert('선택한 항목이 없습니다.');
        }
    });

});


==== ajax.PHP ===

값이 POST 방식으로 전달되는 것만 알 수 있게 연습한 파일이다.

실제로는 MySQL DB와 연동하여 수행처리하는 로직을 만들면 된다.


<?php
if(isset($_POST['chkdata'])){
    /*
    foreach($_POST['chkdata'] as $column => $value) {
        echo $value;
        // MySQL 함수와 연동하여 DB Delete 수행 처리
    }
    */
    $response = implode(" , ",$_POST['chkdata']); // 배열을 문자열로 저장
    echo $response;

    if($response) {

       $sql = "delete from tablename where uid in (".$response.")";

        mysqli_query($dbconn,$sql);

    }

}
?>


=== 테이블을 출력하는 파일 전체 ===

http://link2me.tistory.com/1127 와 비교하여 달라진 부분이 뭔지 보면 알 것이다.


<?php
require_once 'dbconnect.php'; // db접속 성공
require_once 'phpclass/dbClass.php';
require_once 'phpclass/boardClass.php';

$c = new MySQLiDbClass();

$link_url = $_SERVER['PHP_SELF']; // 현재 실행중인 파일명 가져오기
$rowsPage = 12;

// 화면에 출력할 칼럼 발췌

$flddata ="uid,ItemName,Price,Quantity";
$where ="";
$curPage = isset($_GET['p']) ? $_GET['p'] : 1;
$result = $c->getDbArray('items',$where,$flddata,'',$rowsPage,$curPage);
$totalcnt = $c->getDbRows('items',$where);

$d = new boardClass();
?>
<!DOCTYPE html>
<head>
<meta charset=UTF-8" />
<meta name="robots" content="noindex,nofollow"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"/>
<meta http-equiv="X-UA Compatible" control="IE=edge,chrome=1" />
<link rel="stylesheet" type="text/css" href="../css/table.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript" src="../js/display.js"></script>
</head>
<body>
<div class="container">
    <table class="table" width="800">
        <thead>
            <tr>
                <th class="header" width="30"><input type="checkbox" id="checkall" /></th>
                <th class="header" width="100">No</th>
                <th class="header" width="250">아이템</th>
                <th class="header" width="250">가격</th>
                <th class="header" width="200">수량</th>
            </tr>
        </thead>
        <?php
            // 테이블 리스트
            $d->tablelistView_checkbox($result);
        ?>
        <td colspan="5" style="text-align:left;"><span class="btnbox1">선택삭제</span></td>
    </table>
</div>
<?php $d->PageLinkView($link_url,$totalcnt,$rowsPage,$curPage);?>
</body>
</html>

블로그 이미지

Link2Me

,