Where The Streets Have No Name

Dynamically Add/Remove rows in HTML table using JavaScript 본문

Developement/Web

Dynamically Add/Remove rows in HTML table using JavaScript

highheat 2011. 3. 27. 22:47

http://viralpatel.net/blogs/2009/03/dynamically-add-remove-rows-in-html-table-using-javascript.html

<HTML> 
<HEAD> 
	<TITLE> Add/Remove dynamic rows in HTML table </TITLE> 
	<SCRIPT language="javascript"> 
		function addRow(tableID) {
 
			var table = document.getElementById(tableID);
 
			var rowCount = table.rows.length;
			var row = table.insertRow(rowCount);
 
			var cell1 = row.insertCell(0);
			var element1 = document.createElement("input");
			element1.type = "checkbox";
			cell1.appendChild(element1);
 
			var cell2 = row.insertCell(1);
			cell2.innerHTML = rowCount + 1;
 
			var cell3 = row.insertCell(2);
			var element2 = document.createElement("input");
			element2.type = "text";
			cell3.appendChild(element2);
		
			var cell4 = row.insertCell(3);
			var element3 = document.createElement("select");
			element3.name = "fnopcs";
			element3.options[0] = new Option('선택해주세요', '');
			element3.options[1] = new Option('홍길동', '011-111-2222');
			cell4.appendChild(element3);
 
		}
 
		function deleteRow(tableID) {
			try {
			var table = document.getElementById(tableID);
			var rowCount = table.rows.length;
 
			for(var i=0; i<rowCount; i++) {
				var row = table.rows[i];
				var chkbox = row.cells[0].childNodes[0];
				if(null != chkbox && true == chkbox.checked) {
					table.deleteRow(i);
					rowCount--;
					i--;
				}
 
 
			}
			}catch(e) {
				alert(e);
			}
		}
 
	</SCRIPT> 
</HEAD> 
<BODY> 
 
	<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" /> 
 
	<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" /> 
 
	<TABLE id="dataTable" width="350px" border="1"> 
		<TR> 
			<TH>Select</TH> 
			<TH>Sr. No.</TH> 
			<TH>Value</TH> 
			<TH>Value</TH>			
		</TR> 
		<TR> 
			<TD><INPUT type="checkbox" name="chk"/></TD> 
			<TD> 1 </TD> 
			<TD> <INPUT type="text" /> </TD> 			
			<TD> 
				<select name='fnopcs' id='fnopcs'  >
					<option value=''>선택해주세요</option>
					<option value='011-111-2222'>홍길동</option>
					<option value='010-201-3019'>고길동</option>
					<option value='010-1111-7777'>아무개</option>
				</select> 
			</TD>
		</TR> 
	</TABLE> 
 
</BODY> 
</HTML>