IT

[Javascript] tbody 태그의 id 값으로 td 내 input value 가져오는 방법

ARISE&SHINE 2023. 1. 31. 21:28
728x90
반응형

<table style="margin: 15px;">
    <thead>
        <tr>
            <th></th>
            <th>Value #1</th>
            <th>Value #2</th>
            <th>Value #3</th>
            <th>Value #4</th>
            <th>Value #5</th>
        </tr>
    </thead>
    <tbody id="table_body">
        <tr>
            <td style="width: 70px;">Line #1</td>
            <td><input value="aa"/></td>
            <td><input value="bb"/></td>
            <td><input value="cc"/></td>
            <td><input value="dd"/></td>
            <td><input value="ee"/></td>
        </tr>
        <tr>
            <td>Line #2</td>
            <td><input value=""/></td>
            <td><input value=""/></td>
            <td><input value=""/></td>
            <td><input value=""/></td>
            <td><input value=""/></td>
        </tr>
        <tr>
            <td>Line #3</td>
            <td><input value=""/></td>
            <td><input value=""/></td>
            <td><input value=""/></td>
            <td><input value=""/></td>
            <td><input value=""/></td>
        </tr>
    </tbody>
	</table>
	
	<button id="GetValue" style="margin-left: 15px;">Click Here!</button>
    
..

<script type="text/javascript">

$('#GetValue').click(function () {
	
	let rows = document.getElementById("table_body").getElementsByTagName("tr");
	console.log(rows.length); /* tbody tr 갯수 = 3 */
	
	for (var r=0; r<rows.length; r++) {
    
		var cells = rows[r].getElementsByTagName("td");
		
		var cell_2 = cells.item(1).lastChild.value; /* cell_2 = aa */
		var cell_3 = cells.item(2).lastChild.value; /* cell_3 = bb */
		var cell_4 = cells.item(3).lastChild.value; /* cell_4 = cc */
		var cell_5 = cells.item(4).lastChild.value; /* cell_5 = dd */
		var cell_6 = cells.item(5).lastChild.value; /* cell_6 = ee */

	}
    
    });

</script>
</html>

 

 

Point 1. tbody 태그에 id 속성값("table_body")을 지정한다.

Point 2. console.log(rows)를 통해 HTMLCollection 으로 출력되는 것을 확인

Point 3. HTMLCollection 리스트에서 주어진 인덱스의 노드를 반환하는 HTMLCollection.item() 메서드 사용

* 이 때 <td><input value=""></td> 요소를 가져왔다.

 

 

Point 4. HTMLCollection.item() 메서드를 통해 가져온 요소에서 lastchild(<input>)로 접근한다.

Point 5. value를 통해 사용자 input 값을 가져올 수 있다.

728x90
반응형