jquery动态增加text元素以及删除文本内容实例代码

2020-05-16 18:42:47易采站长站整理

这段代码是通过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”/>