当前位置: 移动技术网 > IT编程>开发语言>JavaScript > jQuery实现动态添加、删除按钮及input输入框的方法

jQuery实现动态添加、删除按钮及input输入框的方法

2018年05月10日  | 移动技术网IT编程  | 我要评论

本文实例讲述了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程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网