본문 바로가기
프론트엔드/JavaScript

자바스크립트로 행 추가 하는 방법

by step 1 2021. 10. 29.
반응형
<script>
$(function() {
	// 행추가
	$("#btnAddRow").on("click", function() {
		addRow();
		return false;
	});
	
	<%-- 행추가 --%>
	function addRow() {
		var html = "";
		html += '<tr>';
		html += '<td><input type="text" name="name1"  value="" maxlength="15" /></td>';
		html += '<td><input type="text" name="name2"  value="" maxlength="15" /></td>';
		html += '<td><input type="text" name="name3"  value="" maxlength="15" /></td>';
		html += '<td><input type="text" name="name4"  value="" maxlength="15" /></td>';
		html += '<td><input type="text" name="name5"  value="" maxlength="15" /></td>';
		html += '<td><input type="text" name="name6" value="" maxlength="6" /></td>';
		html += '<td class="last"><a id="btnRemoverow" href=""><img src="${pageContext.request.contextPath}/img/icon/minus_icon.gif" /></a></td>';
		html += '</tr/>';
		$("#row_table tbody").append(html);
		return false;
	}
    
    // 행 삭제
	$("#row_table").on("click", "a[id=btnRemoverow]", function() {
		$(this).closest("tr").remove();
		return false;
	});
 })
 </script>

 

<body style="padding:0; margin:0;">
<form id="form1" name="form1" method="post">

	<div class="popup_wrap_">
		<h2 class="pop_title">행추가</h2>
		<!--행추가 St-->
		<table cellpadding="0" cellspacing="0" border="0" width="100%" summary="행추가" class="pop_table" id = "row_table">
			<caption>행추가</caption>
			<colgroup>
				<col style="width:10%">
				<col style="width:10%">
				<col style="width:10%">
				<col style="width:10%">
				<col style="width:10%">
				<col style="width:10%">
				<col style="width:5%">
			</colgroup>
			<tbody>				
				<tr>
					<th>1</th>
					<th>2</th>
					<th>3</th>
					<th>4</th>
					<th>5</th>
					<th>6</th>
					<th>7</th>
				</tr>
				<tr>
					<c:forEach items="${listRow}" var="listRow" varStatus="status">
						<td><input type="text" name="AUTH_CODE"  value="" maxlength="15" /></td>
						<td><input type="text" name="AUTH_TEXT"  value="" maxlength="20" /></td>
						<td><input type="text" name="AUTH_TEXT"  value="" maxlength="20" /></td>
						<td><input type="text" name="AUTH_TEXT"  value="" maxlength="20" /></td>
						<td><input type="text" name="AUTH_TEXT"  value="" maxlength="20" /></td>
						<td><input type="text" name="AUTH_TEXT"  value="" maxlength="20" /></td>
						<td>
							
						</td>
					</c:forEach>
				</tr>				
			 </tbody>
		</table>
		<!--행추가 En-->
		
		<!--버튼 St-->
		<a href="#" id="btnAddRow"><img src="${pageContext.request.contextPath}/img/icon/plus_icon.gif" /></a>
		<div class="btn_wrap">
			<a href="#" id="btnAdd" class="" ><span class="save_btn">저장</span></a>
		</div>
		<!--버튼 En-->

	</div>

</form>
</body>

히든데이터를 함께 보내줘야할경우에는 td 안에 추가해주고

자바스크립트로 행추가하는 함수에도 td 안에 input type="hidden"으로 넣어주어야 한다.

그래야 배열로 컨트롤러에서 받아서 처리가 가능하다.

반응형