这是我的JsFiddle
填写表单并单击“添加”按钮后,我希望表单数据显示在表格内。有人可以帮我,我怎么能用jquery做。
<div class="form-div">
<form class="form-inline">
<fieldset>
<legend>Item Details</legend>
<label>Enter Item Name</label>
<input type="text" placeholder="Item Name">
<label>Quantity</label>
<select class="input-mini">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<button class="btn">Add Data</button>
</fieldset>
</form>
</div>
<div class="table-div">
<table class="table">
<thead>
<tr>
<th> S.no </th>
<th> Item Name </th>
<th> Quantity </th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
答案 0 :(得分:4)
您应该为要操作的元素提供唯一标识符。之后,您可以使用click()
,val()
和append()
jQuery函数执行此类操作:
var sno = 0;
$("form button.btn").click(function() {
var item_name = $("#item_name").val();
var quantity = $("#quantity").val();
var new_row = "<tr><td>" + ++sno + "</td><td>" + item_name + "</td><td>" + quantity + "</td></tr>";
$("table tbody").append(new_row);
return false;
});
如果ID
form
和table
元素在窗口中不是唯一的,并且优化DOM选择,则最好给它们。{/ p>
答案 1 :(得分:2)
答案 2 :(得分:-1)
试试这个
<div class="">
<fieldset>
<legend>Item Details</legend>
<label>Enter Item Name</label>
<input type="text" placeholder="Item Name" id="item_name">
<label>Quantity</label>
<select class="input-mini" id="quentity">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<button class="btn" onclick="viewRecord()">Add Data</button>
</fieldset>
</div>
<div class="">
<table class="table controls controls-row">
<thead>
<tr id="heading">
<th> S.no </th>
<th> Item Name </th>
<th> Quantity </th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
js part
var index=0;
function viewRecord(){
index++;
$('table tbody').append('<tr><td>'+index+'</td><td>'+$("#item_name").val()+' </td><td> '+$("#quentity option:selected").val()+'</td></tr>');
}
<强> Working Demo 强>