JSFiddle - React, Tailwind, and code Playground

by tomboliu

HTML

<button type="button" id="addField">Add Input Field</button>
<div id="inputzone">
	<div class="fieldwrapper" id="field1">
		<input type="text" name="money1" class="inputMoney" placeholder="請輸入金額" />
		<input type="text" name="memo1" class="inputMEMO" placeholder="請輸入說明" />
	</div>
</div>

CSS

body
{
    font-family:Gill Sans MT;
    padding:10px;
}
input#addField
{
    float:right;
}
input.inputMoney
{
    float:left;
	/* 如果沒有 clear:left; 會造成新增欄位一路橫排 */
	clear:left;
	display:block;
    margin:5px;
}
input.inputMEMO
{
    float:left;
	display:block;
    margin:5px;
}
input.remove
{
    float:left;
    display:block;
    margin:5px;
    width:25px;
	font-size:16px;
    font-weight: bold;
    text-align:center;

	-webkit-border-radius: 10px;
	-moz-border-radius: 10px;
	border-radius: 10px;
	border:2px solid #FFFF00;
	background-color:lightblue;
}
input.remove:hover{
    background-color:lightgreen;
}
input.remove:active{
    background-color:pink;
}
}

JavaScript

$(function(){
	$("#addField").click(function(){
		var intId = $(".fieldwrapper").size() + 1;
		var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
		var fMoney = $("<input type=\"text\" name=\"money"+ intId + "\" class=\"inputMoney\" placeholder=\"請輸入金額\" />");
		var fMemo = $("<input type=\"text\" name=\"memo"+ intId + "\" class=\"inputMEMO\" placeholder=\"請輸入說明\" />");
		var removeButton = $("<input type=\"button\" class=\"remove\" value=\"-\" />");
		removeButton.click(function() {
			$(this).parent().remove();
			<!-- 移除欄位後,將 ID 重新設定順序,避免空號,造成下次新增欄位時,ID 重覆 -->
			var wrappers = $(".fieldwrapper");
			if (wrappers.length > 1) {
				var newId = 1;
				wrappers.each(function(){
					renewId = "field" + newId;
					$(this).attr("id",renewId);
					newId++;
				});
			}
		});
		
		fieldWrapper.append(fMoney);
		fieldWrapper.append(fMemo);
		fieldWrapper.append(removeButton);
		$("#inputzone").append(fieldWrapper);
	});
});