原生js+html+css實現從表單(form)動態加數據到表格(table)

css部分

<style>
			.info{
				width: 150px;
				margin-bottom: 10px;
			}
			th{
				width: 100px;
				padding-left: 5px;
			}
			.title{
				height: 30px;
				background: purple;
				color: white;
			}
			td{
				height: 30px;
				padding-left: 5px;
			}
		</style>

html部分

<form action="#" method="post">
			<label for="brand">品牌:</label><input class="info" type="text" name="name" id="brand" placeholder="請輸入品牌" /><br />
			<label for="model">型號:</label><input class="info" type="text" name="model" id="model" placeholder="請輸入產品型號" /><br />
			<label for="parameter">參數:</label><input class="info" type="text" name="parameter" id="parameter" placeholder="請輸入產品參數" /><br />
			<label for="price">價格:</label><input class="info" type="text" name="price" id="price" placeholder="請輸入產品價格" /><br />
			<label for="country">國別:</label>
			<select style="width: 150px;margin-bottom: 10px;" name="country" id="country">
				<option value="">請選擇</option>
				<option value="中國">中國</option>
				<option value="美國">美國</option>
				<option value="法國">法國</option>
				<option value="韓國">韓國</option>
				<option value="德國">德國</option>
				<option value="英國">英國</option>
			</select><br />
			<input type="button" id="btn" value="添加信息" />
		</form>
		<table border="1" cellspacing="0" cellpadding="0" style="text-align: left;margin-top: 20px;">
			<tr class="title">
				<th>品牌</th>
				<th>型號</th>
				<th>參數</th>
				<th>價格</th>
				<th>國別</th>
			</tr>
		</table>

js部分

<script>
			var btn = document.getElementById('btn');
			btn.onclick = function(){
				var brand = document.getElementById('brand').value;
				var model = document.getElementById('model').value;
				var parameter = document.getElementById('parameter').value;
				var price = document.getElementById('price').value;
				var country = document.getElementById('country').value;
				if(brand=="" | model=="" | parameter=="" | price== "" | country == ""){
					alert("輸入的信息不完整,請輸入完整信息");
				}else{
					var table = document.getElementsByTagName('table')[0];
					var tr = document.createElement('tr');
					tr.innerHTML = "<td>"+brand+"</td><td>"+model+"</td><td>"+parameter+"</td><td>"+price+"</td><td>"+country+"</td>";
					table.appendChild(tr);
				}
				
			}
		</script>

運行截圖
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章