문자열에 특정 문자가 포함되어 있는지 확인

# Check 함수
function strpos_array($haystack, $needle) {
    $pos = FALSE;
    if (!is_array($needle)) $needle = array($needle);
    foreach ($needle as $what) {
        if (($pos = strpos($haystack, $what)) !== FALSE) {
            return $pos;
        }
    }
    return FALSE;
}

$filters = array("TEST", "test", "Pass", "PASS");
$strText = "The TEST Code !!"
if (strpos_array($strText, $filters) !== false) {
    // nothing to do
    echo json_encode("Text has been filtered");
    return;
}

기능

chart에 value를 동적으로 추가

backgroundColor를 랜덤하게 설정 ( 결과가 Fix 되지않은 chart 리스트를 추가 할때 사용 )

 

// html
<canvas id="cChart"></canvas>

// javascript
var Chart_ctx = document.getElementById('cChart').getContext('2d');

// Chart Config
Chart_config = {
    type: 'pie',
    data: ..........
}

// Chart Create
var Chart = new Chart(Chart_ctx, Chart_config);


// Chart Data 동적 추가
Chart_config.data.datasets[0].data.push(1);

// Set backgroundColor 랜덤하게 값 추가 ( 투명도 30% )
var RGB_1 = Math.floor(Math.random() * (255 + 1))
var RGB_2 = Math.floor(Math.random() * (255 + 1))
var RGB_3 = Math.floor(Math.random() * (255 + 1))
var strRGBA = 'rgba(' + RGB_1 + ',' + RGB_2 + ',' + RGB_3 + ',0.3)'
Chart_config.data.datasets[0].backgroundColor.push(strRGBA);

참고

https://stackoverflow.com/questions/23095637/how-do-you-get-random-rgb-in-javascript

기능

1. Chart.js 2.x 버전 Pie Chart

2. 파이 차트 클릭 이벤트 ( Pie Chart Click Event ) - label 및 value 조회

3. 마우스 오버없이 레이블을 항상 백분율(%)값을 표시

 

html

* chart를 그리기 위한 canvas를 생성

* 다른 로직에서 canvas를 참고하기 위해 id를 지정 ( 예제는 cPieChart 으로 생성 )

<canvas id="cPieChart" style="min-height: 500px; height: 500px; max-height: 1000px; width: 700px; max-width: 100%;"></canvas>

javascript

* chart.js를 사용하기 위해 Chart.min.js 를 추가

* 마우스 오버없이 레이블을 항상 표시하기 위한 chartjs-plugin-datalabels@0.7.0 추가

 

* config의 data -> datasets -> datalabels 부분에 설정값을 지정

   align : 레이블 위치

   backgroundColor : ctx 정보를 가져와서 value가 0 이상인 경우만 출력

   color : ctx 정보를 가져와서 value가 0 이상인 경우만 출력

   formatter : value, ctx 정보를 가져와서 0 이상인 경우 백분율값을 구하여 리턴

 

* Pie Chart 생성 후 onClick Event 값을 가져와서 이벤트 처리

  getElementsAtEvent(evt) 함수로 클릭 이벤트 값을 조회

  activePoints[0]["_index"] 로 클릭한 차트의 위치값을 조회

   >> 만약 하나의 canvas에 여러개의 chart가 있는 경우 아래 형태로 조회

        activePoints[0]["_index"]

        activePoints[1]["_index"]

        activePoints[2]["_index"]

 

<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.7.0"></script>

// Pie Chart ctx Get
var PieChart_ctx = document.getElementById('cPieChart').getContext('2d');

// Pie Chart Config Set
PieChart_config = {
    type: 'pie',
    data: {
        labels: ['OPEN', 'PROGRESSING', 'COMPLETE'],
        data: [13,11,14],
        datasets: [{
            label: 'Pie Chart Count',
            backgroundColor: [
                        'rgba(255, 99, 132, 0.2)',
                        'rgba(54, 162, 235, 0.2)',
                        'rgba(75, 192, 192, 0.2)'
                        ],
            borderColor: [
                        'rgba(255, 99, 132, 1)',
                        'rgba(54, 162, 235, 1)',
                        'rgba(75, 192, 192, 1)'
                        ],
            borderWidth: 1,
            datalabels: {
                labels: {
                    value: {
                        borderWidth: 2,
                        borderRadius: 4,
                        font: {size: 15},
                        formatter: function(value, ctx) {
                            var value = ctx.dataset.data[ctx.dataIndex];
                            return value > 0 ? Math.round(value / (ctx.dataset.data[0] + ctx.dataset.data[1] + ctx.dataset.data[2]) * 100) + ' %' : null;
                        },
                        color: function(ctx) {
                            var value = ctx.dataset.data[ctx.dataIndex];
                            return value > 0 ? 'white' : null;
                        },
                        backgroundColor:function(ctx) {
                            var value = ctx.dataset.data[ctx.dataIndex];
                            return value > 0 ? 'gray' : null;
                        },
                        padding: 4
                    }
                }
            }
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio : false,
        animation: false,
        legend: {
            position: 'left',
            display: true
        },
        title: {
            display: false,
            text: 'Pie Chart - Count',
            font: {
                size: 50
            },
            fontstyle: 'bold',
            position: 'top'
        }, 
        plugins: {
            legend: {
                position: 'left',
            },
            title: {
                display: true,
                text: 'Pie Chart - Count',
                font: { 
                    size: 25
                }
            }
        }
    }
};


// Pie Chart Create
var PieChart = new Chart(PieChart_ctx, PieChart_config);

// Pie Chart Event Set
document.getElementById("cPieChart").onclick = function(evt) {

    var activePoints = PieChart.getElementsAtEvent(evt);

    if(activePoints.length > 0)
    {
        //get the internal index of slice in pie chart
        var clickedElementindex = activePoints[0]["_index"];

        //get specific label by index 
        var label = PieChart.data.labels[clickedElementindex];

        //get value by index      
        var value = PieChart.data.datasets[0].data[clickedElementindex];

        // label and value Process
        
   }
};

참고

https://stackoverflow.com/questions/26257268/click-events-on-pie-charts-in-chart-js

https://chartjs-plugin-datalabels.netlify.app/samples/charts/line.html

https://chartjs-plugin-datalabels.netlify.app/samples/advanced/multiple-labels.html

 

Multiple Labels | chartjs-plugin-datalabels

Multiple Labels Use multiple labels configuration to display 3 labels per data, one for the index, one for the label and one for the value. Move the mouse over the chart to display label ids. { type: 'doughnut', data: { labels: labels, datasets: [{ backgro

chartjs-plugin-datalabels.netlify.app

 

AdminLTE

https://adminlte.io/

 

Free Bootstrap Admin Template | AdminLTE.IO

Bootstrap is raking over the world and so is React. Therefore, we decided to showcase these outstanding React Bootstrap templates May 18, 2021

adminlte.io

W3schools

https://www.w3schools.com/html/default.asp

 

HTML Tutorial

HTML Tutorial HTML is the standard markup language for Web pages. With HTML you can create your own Website. HTML is easy to learn - You will enjoy it! Start learning HTML now » Easy Learning with HTML "Try it Yourself" With our "Try it Yourself" editor,

www.w3schools.com

javatpoint

https://www.javatpoint.com/html-tutorial

 

Learn HTML Tutorial - javatpoint

Learn HTML Tutorial or HTML 5 Tutorial for beginners and professionals with tags, elements, tables, forms, anchor, image, heading, marquee, textarea, div, audio, video, header, footer etc.

www.javatpoint.com

DataTables

https://datatables.net/examples/index

 

DataTables examples - Examples index

Examples index One of the best ways to learn how to do anything new (including software APIs!) is to get your hands dirty as quickly as possible. These examples will show you how to perform tasks ranging from something as simple as applying DataTables to a

datatables.net

html

<table id="example" class="stripe" style="width:100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Tiger Nixon</td>
                <td>System Architect</td>
                <td>Edinburgh</td>
                <td>61</td>
                <td>2011/04/25</td>
                <td>$320,800</td>
            </tr>
            <tr>
                <td>Garrett Winters</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>63</td>
                <td>2011/07/25</td>
                <td>$170,750</td>
            </tr>
            <tr>
                <td>Ashton Cox</td>
                <td>Junior Technical Author</td>
                <td>San Francisco</td>
                <td>66</td>
                <td>2009/01/12</td>
                <td>$86,000</td>
            </tr>
            <tr>
                <td>Cedric Kelly</td>
                <td>Senior Javascript Developer</td>
                <td>Edinburgh</td>
                <td>22</td>
                <td>2012/03/29</td>
                <td>$433,060</td>
            </tr>
            <tr>
                <td>Airi Satou</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>33</td>
                <td>2008/11/28</td>
                <td>$162,700</td>
            </tr>
            
            ............
            
            <tr>
                <td>Donna Snider</td>
                <td>Customer Support</td>
                <td>New York</td>
                <td>27</td>
                <td>2011/01/25</td>
                <td>$112,000</td>
            </tr>
        </tbody>
        <tfoot>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </tfoot>
    </table>

javascript

$(document).ready(function() {
    $('#example').DataTable();
} );

In addition to the above code, the following Javascript library files are loaded for use in this example:

https://code.jquery.com/jquery-3.5.1.js
https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js

css

The following CSS library files are loaded for use in this example to provide the styling of the table:

https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css

참고

https://datatables.net/examples/styling/stripe.html

 

DataTables example - Base style - stripe

Base style - stripe This example shows DataTables with just the stripe class specified. Name Position Office Age Start date Salary Tiger Nixon System Architect Edinburgh 61 2011/04/25 $320,800 Garrett Winters Accountant Tokyo 63 2011/07/25 $170,750 Ashton

datatables.net

javascript

var json = { 'NAME':'홍길동', 'SEX':'남', 'AGE':'99세'};

for(key in json) {
    alert('key:' + key + ' / ' + 'value:' + json[key]);
}

jquery

var json = { 'NAME':'홍길동', 'SEX':'남', 'AGE':'99세'}; 

$.each(json, function(key, value){
    alert('key:' + key + ' / ' + 'value:' + value);
});

참고

https://gent.tistory.com/17

 

[javascript|자바스크립트] foreach 구문을 이용하여 JSON 값 쉽게 가져오기 (json key get value)

자바스크립트의 foreach 구문을 이용하여 JSON 객체의 키(key)와 값(value)를 쉽게 가져올 수 있다. jQuery를 사용한다면 $.each 구문을 대신 사용할 수도 있다. ■ Javascript var json = { 'NAME':'홍길동', 'S..

gent.tistory.com

html의 td style 부분에 아래 내용을 추가

{ white-space:pre-line , word-break: break-all}

<table id="test_table">
  <thead>
    <tr>
      <th style="text-align:center;">ID</th>
      <th style="text-align:center;">Info Detail</th>
      <th style="text-align:center;">Date</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td> 1 </td>
      <td style="white-space:pre-line;word-break: break-all;">
        Info 1
        Info 2
        Value 1
        Value 2
      </td>
      <td>'2021-07-10 09:00:00' 
      </td>
    </tr>
  </tbody>
  <tfoot>
  </tfoot>
</table>

참고

https://stackoverflow.com/questions/10937218/how-to-show-multiline-text-in-a-table-cell

 

How to show multiline text in a table cell

I want to show a paragraph from database into a table cell. The result is a large 1 line, ignoring how its organised in database. ignoring 'enters' for example (new lines) I want to show it exactly

stackoverflow.com

1. 테이블 행(row) 클릭 시 해당 행의 값을 가져오기

html

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">    
    <!-- jQuery  -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <!-- bootstrap JS -->
    <script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>   
    <!-- bootstrap CSS -->
    <link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
</head>
 
<body>  
    <br><br>
    <div class="row">
        <table id="example-table-1" width="100%" class="table table-bordered table-hover text-center">
            <thead>
                <tr>
                    <th>No. </th>
                    <th>아이디</th>
                    <th>이름</th>
                    <th>이메일</th>
                </tr>
            </thead>
            <tbody>                
                <tr>
                    <td>1</td>
                    <td>user01</td>
                    <td>홍길동</td>
                    <td>hong@gmail.com</td>
                </tr>
                <tr>
                    <td>2</td>
                    <td>user02</td>
                    <td>김사부</td>
                    <td>kim@naver.com</td>
                </tr>
                <tr>
                    <td>3</td>
                    <td>user03</td>
                    <td>존</td>
                    <td>John@gmail.com</td>
                </tr>
            </tbody>
        </table>
        <div class="col-lg-12" id="ex1_Result1" ></div> 
        <div class="col-lg-12" id="ex1_Result2" ></div> 
    </div>
    <br><br>     
</body>
</html>

javascript

<script>
    // 테이블의 Row 클릭시 값 가져오기
    $("#example-table-1 tr").click(function(){     
        var str = ""
        var tdArr = new Array();    // 배열 선언
            
        // 현재 클릭된 Row(<tr>)
        var tr = $(this);
        var td = tr.children();
            
        // tr.text()는 클릭된 Row 즉 tr에 있는 모든 값을 가져온다.
        console.log("클릭한 Row의 모든 데이터 : "+tr.text());
            
        // 반복문을 이용해서 배열에 값을 담아 사용할 수 도 있다.
        td.each(function(i){
            tdArr.push(td.eq(i).text());
        });
            
        console.log("배열에 담긴 값 : "+tdArr);
            
        // td.eq(index)를 통해 값을 가져올 수도 있다.
        var no = td.eq(0).text();
        var userid = td.eq(1).text();
        var name = td.eq(2).text();
        var email = td.eq(3).text();
            
            
        str += " * 클릭된 Row의 td값 = No. : <font color='red'>" + no + "</font>" +
               ", 아이디 : <font color='red'>" + userid + "</font>" +
               ", 이름 : <font color='red'>" + name + "</font>" +
               ", 이메일 : <font color='red'>" + email + "</font>";        
          
        $("#ex1_Result1").html(" * 클릭한 Row의 모든 데이터 = " + tr.text());        
        $("#ex1_Result2").html(str);
    });    
</script>

2. 버튼 클릭 시 해당 행(row)의 값을 가져오기

html

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <!-- jQuery  -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>   
    <!-- bootstrap JS -->
    <script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
    <!-- bootstrap CSS -->
    <link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"> 
</head>
 
<body>   
    <br><br>
    <div class="row">
        <table id="example-table-2" width="100%" class="table table-bordered table-hover text-center">
            <thead>
                <tr>
                    <th>No. </th>
                    <th>아이디</th>
                    <th>이름</th>
                    <th>이메일</th>
                    <th>버튼</th>
                </tr>
            </thead>
            <tbody>                
                <tr>
                    <td>1</td>
                    <td>user04</td>
                    <td>맥크리</td>
                    <td>sunset@gmail.com</td>
                    <td><input type="button" class="checkBtn" value="클릭" /></td>
                </tr>
                <tr>
                    <td>2</td>
                    <td>user05</td>
                    <td>메르시</td>
                    <td>Mercy@naver.com</td>
                    <td><input type="button" class="checkBtn" value="클릭" /></td>
                </tr>
                <tr>
                    <td>3</td>
                    <td>user06</td>
                    <td>한조</td>
                    <td>trolling@gmail.com</td>
                    <td><input type="button" class="checkBtn" value="클릭" /></td>
                </tr>
            </tbody>
        </table>
        <div class="col-lg-12" id="ex2_Result1" ></div> 
        <div class="col-lg-12" id="ex2_Result2" ></div> 
    </div> 
    <br><br> 
</body>
</html>

javascript

<script>
    // 버튼 클릭시 Row 값 가져오기
    $(".checkBtn").click(function(){ 
            
        var str = ""
        var tdArr = new Array();    // 배열 선언
        var checkBtn = $(this);
            
        // checkBtn.parent() : checkBtn의 부모는 <td>이다.
        // checkBtn.parent().parent() : <td>의 부모이므로 <tr>이다.
        var tr = checkBtn.parent().parent();
        var td = tr.children();
            
        console.log("클릭한 Row의 모든 데이터 : "+tr.text());
            
        var no = td.eq(0).text();
        var userid = td.eq(1).text();
        var name = td.eq(2).text();
        var email = td.eq(3).text();
            
            
        // 반복문을 이용해서 배열에 값을 담아 사용할 수 도 있다.
        td.each(function(i){    
            tdArr.push(td.eq(i).text());
        });
            
        console.log("배열에 담긴 값 : "+tdArr);
            
 
        str += " * 클릭된 Row의 td값 = No. : <font color='red'>" + no + "</font>" +
               ", 아이디 : <font color='red'>" + userid + "</font>" +
               ", 이름 : <font color='red'>" + name + "</font>" +
               ", 이메일 : <font color='red'>" + email + "</font>";        
            
        $("#ex2_Result1").html(" * 클릭한 Row의 모든 데이터 = " + tr.text());        
        $("#ex2_Result2").html(str);    
    }); 
</script>

참고

https://all-record.tistory.com/172

html

<button id="my-btn" onclick="alert('클릭이벤트 발생')";>버튼</button>

js

//JQuery
$("#my-btn").trigger("click");

//javascript
document.getElementById("my-btn")[0].click();

참고

https://6developer.com/6

html에서 select2 id값을 설정

javascript에서 id값으로 html의 select2 값을 조회 및 변경

<!DOCTYPE html>
<html>
  <head>
    <title>Select2 Test</title>
    <!-- select2 css cdn -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.9/css/select2.min.css" rel="stylesheet" />
  </head>
  <body>
    <br />
    <div style="margin-left:10px;">
      <select class="form-control select2" id="search_type" name="search_type">
        <option value="all">ALL</option>
        <option value="sql">SQL</option>
        <option value="os">OS</option>
      </select>
    </div>

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <!-- select2 javascript cdn -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.9/js/select2.min.js"></script>
    <script>
    
      //Initialize Select2 Elements
      $('.select2').select2({
        theme: "bootstrap4",
        width: 'auto',
        dropdownAutoWidth: true
      })
      
      //select2 선택값 변경
      $('#search_type').val('OS');
      // 위 코드로 변경이 되지 않는 경우
      $('#search_type').val('OS').trigger('change');
       
    </script>
  </body>
</html>

to Top