[html, css, js] 테이블 관련 코딩 팁

망고고래 2025. 1. 24. 11:41

1. html

 

2. css

1) 페이지 너비 축소시 글자가 삐져나감

td{
    word-wrap: break-word;
}

단어가 한 줄에 모두 들어가지 않을 경우 줄바꿈을 한다.

영어는 단어 중간에 줄이 바뀌면 알아보기 어려워서 break-word가 기본값이 아닌 듯하다.

 

3. javascript

1) 라디오, 체크박스가 선택되어있는 행 가져오기

var table = document.getElementById('TableId');

//라디오
var selectedRow = table.querySelector('input [type="radio"]:checked').closest('tr');
//체크박스
var selectedRows = table.querySelectorAll('input [type="checkbox"]:checked);
//체크박스 - 마스터 체크박스 제외
var selectedRows2 = table.querySelectorAll('input [type="checkbox"]:checked:not(#masterCheckbox)');

 

2) 값이 null인 경우 공백으로 출력

//null 대응
cell.textContent = value || '';

//문자열 'null' 대응
cell.textContent = value === 'null' ? '' : (value || '');

 

① value === 'null'

문자열 'null'과의 일치 여부 판단. true일 경우 공백 출력, false일 경우 괄호로 넘어감

② (value || '')

value가 truthy*일 경우(값이 있음) value 출력, falsy**일 경우(값이 없음: null) 공백 출력

 

*truthy: boolean 문맥에서 true로 평가되는 값. falsy 값을 제외한 값이 해당됨.
**falsy: boolean 문맥에서 false로 평가되는 값. null, undefined, false, NaN, 공백 등이 포함됨.

 


25.03.05.

3) display: none인 행 연산에서 제외하기

(row.style.display !== none)의 연산 결과 사용

rows = document.querySelectorAll('#TableForCal tbody tr');
let totalAmount = 0;

rows.forEach(row => {
    if(row.style.display !== 'none'){ //보이지 않는 행 연산에서 제외
        const inputs = row.getElementsByTagName('input');
        const amountInput = Array.from(inputs).find(input => input.name === 'data_am');
        if(amountInput && amountInput.value){
            totalAmount += Number(amountInput.value);
        }
    }
});


다른 코드의 일부를  가져와서 약간 변경한 코드이다.

동적으로 생성된 행이라 input을 querySelector로 찾지 못하는 문제가 있었다. 그래서 행의 모든 input을 배열로 만들고 그 배열 안에서 find를 사용해 찾도록 해서 코드가 조금 길어졌다.

 

 

25.03.07.

4) 행 클릭시 행의 정보로 연산하기

function eventListenerFunction(){
    const table = document.getElementById('table');
    table.onclick = handleRowData;
}

function handleRowData(event){
    const targetElement = event.target;
    const dataRow = targetElement.tagName === 'TD' ?
        targetElement.parentElement : targetElement.closest('tr');
    
    if(!dataRow) return;
    
    //dataRow로 필요 동작 수행
}

 

 

 

25.03.12.

5) 행 클릭시 라디오 버튼 체크

행에 이벤트 리스너 설치

const row = tbody.insertRow();
row.innerHTML = `
    <td><input type="radio"></td>
    <td> ...
`;

row.addEventListener('click', function(e) {
    radio.checked = true;
});

 

 

6) 행 클릭과 라디오 버튼 클릭 모두에 대응하기

function calledFunction(event){
    const targetElement = event.target;
    const dataRow = targetElement.tagName === 'TD' ?  //td(셀)인지 확인
        targetElement.parentElement :    //맞는 경우 td의 부모인 tr(행) 선택
        targetElement.closest('tr');     //아닌 경우(라디오 버튼) 가장 가까운 tr(행) 선택
}