본문 바로가기

Web For All

jQuery에서 테이블의 row 추가 혹은 삭제


function fnAddRow(tbName) {
	try {
		// 테이블을 찾아서 로우 추가
		var tbody = $('#' + tbName + ' tbody');
		var rows = tbody.find('tr').length;
		var newRow = tbody.find('tr:last').clone(true).appendTo(tbody);

		fnControlInit(newRow, rows);

		// rno가 있으면 숫자를 입력
		newRow.find("span[id^=rno]").html(rows + 1);

		// 해외 유학경험의 달력 필드가 있으면 이벤트 바인딩
		newRow.find(":text[id^=txtStudyStartDate]").simpleDatepicker({ startdate: 1980 });
		newRow.find(":text[id^=txtStudyEndDate]").simpleDatepicker({ startdate: 1980 });
	}
	catch (e) {
		alert(e.Message);
	}
}

function fnRemove(obj) {
	try {
		// 현재 선택된 오브젝트의 상위 tr을 찾아서 삭제~
		var rows = $(obj).parent().parent().parent().parent().parent("tbody").find('> tr');
		var table = $(obj).parent().parent().parent().parent().parent().parent();
		
		if (table.attr("id") != "tbWDHChild" && rows.length > 2) {
			$(obj).parent().parent().parent().parent().remove();

			// 삭제시 아이디 값이 중복되는 현상으로 인해 아이디 값 재 설정.
			$(table).find("table[id^=tbWDHChild]").each(function (i) {
				var id = this.id
				if (id)
					this.id = this.id.split('_')[0] + '_' + i;
			});
		}
		else if(table.attr("id") == "tbWDHChild" && rows.length > 1){
			$(obj).parent().parent().parent().parent().remove();

			var i = 0;
			// 삭제시 아이디 값이 중복되는 현상으로 인해 아이디 값 재 설정.
			$(table).find("table[id^=tbWDHChild]").each(function (i) {
				var id = this.id
				if (id)
					this.id = this.id.split('_')[0] + '_' + i;
			});
		}

		table = $(rows).parent().parent();
		if (table.attr("id").indexOf("tbWDHChild") >= 0) {
			var tbody = $(table).find("tbody");
			tbody.find('> tr').each(function (i) {
				$(this).find("> td > div > span[id^=rno]").html(i + 1);
			});
		}
	}
	catch (e) {
		alert(e.Message);
	}
}

function fnControlInit(jRowobj, rowCnt){
	// input tag를 찾아서 value 지움
	jRowobj.find(':input').val('').each(function () {
		var id = this.id
		if (id) {
			this.id = this.id.split('_')[0] + '_' + rowCnt;
		}
	});
}


참조사이트: http://angeleyes.tistory.com/228