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

2019-12-15 16:00:26来源:爱站网 阅读 ()

新老客户大回馈,云服务器低至5折

我们在开发项目的时候都需要使用jQuery进行开发,那么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实现动态添加、删除按钮及input输入框的方法,该介绍完成之后,就能进入项目体现效果,享受编程的乐趣了。


原文链接:https://js.aizhan.com/develop/JavaScript/10725.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Angular.js中定时器循环的3种方法

下一篇:JS实现数组按升序及降序排列的方法