jQuery动态添加与删除input输入框及按钮的实现
作者:橙子时间:2026-10-22 03:35:47浏览:452
本文介绍使用jQuery实现动态添加和删除input输入框及按钮的方法。通过点击按钮动态生成新的输入框,并支持移除已添加的输入框,适用于需要灵活表单字段的场景。
jQuery动态添加与删除input输入框及按钮的实现
本文介绍如何使用jQuery实现动态添加和删除按钮以及input输入框的功能。
<html>
<head>
<meta charset="utf-8">
<title>动态创建按钮</title>
<script src='http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js'></script>
</head>
<body>
<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="AddMoreFileBox" class="btn btn-info">添加更多的input输入框</a></span></p>
<div id="InputsWrapper">
<div><input type="text" name="mytext[]" id="field_1" value="Text 1"/><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="removeclass"><input type='button' value='删除'></a></div>
</div>
<script>
$(document).ready(function() {
var MaxInputs = 8; //maximum input boxes allowed
var InputsWrapper = $("#InputsWrapper"); //Input boxes wrapper ID
var AddButton = $("#AddMoreFileBox"); //Add button ID
var x = InputsWrapper.length; //initlal text box count
var FieldCount=1; //to keep track of text box added
$(AddButton).click(function (e) //on add input button click
{
if(x <= MaxInputs) //max input box allowed
{
FieldCount++; //text box added increment
//add input box
$(InputsWrapper).append('<div><input type="text" name="mytext[]" id="field_'+ FieldCount +'" value="Text '+ FieldCount +'"/><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="removeclass"><input type="button" value="删除"></a></div>');
x++; //text box increment
}
return false;
});
$("body").on("click",".removeclass", function(e){ //user click on remove text
if( x > 1 ) {
$(this).parent('div').remove(); //remove text box
x--; //decrement textbox
}
return false;
})
});
</script>
</body>
</html>
运行效果如下图所示:

更多关于jQuery相关内容感兴趣的读者可查看本站专题:《jQuery常见事件用法与技巧总结》、《jQuery常用插件及用法总结》、《jQuery操作json数据技巧汇总》、《jQuery扩展技巧总结》、《jQuery拖拽特效与技巧总结》、《jQuery表格(table)操作技巧汇总》、《jQuery常见经典特效汇总》、《jQuery动画与特效用法总结》及《jquery选择器用法总结》
希望本文所述对大家jQuery程序设计有所帮助。
作者最新文章
JS脚本在App中运行报错怎么解决
2026-11-04 23:11:03
JS怎么使用padStart方法给数字补零
2026-11-04 11:12:03
JS是什么意思?JavaScript全称及基本定义
2026-11-04 08:05:29
JS 使用 toFixed(1) 保留一位小数的基本用法与注意事项
2026-11-03 18:34:57
JS字符串转整数:parseInt与Number的区别及用法
2026-11-03 17:26:54
