萬盛學電腦網

 萬盛學電腦網 >> 腳本專題 >> javascript >> jquery動態增加text元素以及刪除文本內容實例代碼

jquery動態增加text元素以及刪除文本內容實例代碼

這段代碼是通過jquery動態增加限定數額的text(本例為5個) ,以及清除文本內容,用到了after()方法追加元素。
<!--以下為script代碼開始-->

復制代碼 代碼如下:
<script>
$(document).ready(function(){
var spotMax = 5;//限定添加text元素的總個數
var afterId = 0;//要追加元素的id
var newId=1;//新生成text的id
if($('table#vote').size() >= spotMax) {}
$("#btnAddOption").click(function(){
afterId++;
newId=afterId+1;
addSpot(this, spotMax,afterId,newId);
});
});
//添加選項方法
function addSpot(obj, sm,afterId,newId) {
if($('tr.spot').size() < sm){
$('#vote_'+afterId).after(
'<tr id="vote_'+newId+'" class="spot"><th>'+afterId+'</th>' +
'<td><input type="text" id="txtInput_'+afterId+'" class="input-text" value="" size="40" name="names" /></td> ' +
'</tr>');
$(":text[id^='txtInput_']").val("輸入文本...");//給新增的文本賦予初始值
}
else{
alert("最多只能添加5項投票!");
}
};
//重置選項
$("input#btnResetOption").click(function(){
$(":text[id^='txtInput_']").val("");//清空文本內容
});
</script>


<!--以下為script代碼結束-->
<!--以下為html代碼塊開始-->

復制代碼 代碼如下:
<form method='post' id="updateForm" action="admin/vote/doVote">
<table cellpadding=0 cellspacing=0 width="100%" class="table_form">
<tr>
<th width="140">投票名稱</th>
<td>
<input type="text" id="txtName" name="name" class="input-text" value="" size="85"/>
</td>
</tr>
<tr>
<th width="140">投票描述</th>
<td>
<textarea id="txtDescribe" class="input-text" name="remark" cols="85" ></textarea>
</td>
</tr>
<tr>
<th width="140">開始時間</th>
<td>
<input type="text" id="dateMin" class="input-text" value="" name="startDate" size="40" readonly="readonly"/>
</td>
</tr>
<tr>
<th width="140">結束時間</th>
<td>
<input type="text" id="dateMax" class="input-text" name="endDate" size="40" readonly="readonly"/>
</td>
</tr>
<tr>
<th width="140">是否多選</th>
<td>
<input type="radio" id="txtEndTime" name="isSelect" value="0" size="40"/>單選
<input type="radio" id="txtEndTime" name="isSelect" value="1" size="40"/>多選
</td>
</tr>
<tr id="vote_1">
<th width="140">投票選項</th>
<td>
<input type="button" id="btnAddOption" name="btnAddOption" class="button" value="添加選項"/>
<input type="reset" id="btnResetOption" name="btnResetOption" class="button" value="重置選項"/>
</td>
</tr>
<tr id="save">
<th></th>
<td align="left">
<input type="submit" id="btnSave" name="btnSave" class="button" style="width:50px" value="保存"/>
<input type="submit" id="btnClose" name="btnClose" class="button" style="width:50px" value="取消"/>
</td>
</tr>
</table>
</form>


<!--以下為html代碼塊開始-->
以下是運行效果:

copyright © 萬盛學電腦網 all rights reserved