MVC中用jQuery加BootStrap实现动态增加删除文本输入框!
http://www.freejs.net/article_biaodan_278.html
这是在网上找到方法,我修改了一下实合我的项目,发博只为收藏记录并加深记忆。
修改后效果如下
@model PwtsWeb.Models.PhoneNum @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <link href="~/Content/bootstrap.min.css" rel="stylesheet" /> <link href="~/Content/bootstrap-theme.min.css" rel="stylesheet" /> <title>UserAdd</title> </head> <body> <!-- 模态框(Modal) --> <div class="modal show" id="userAdd" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> × </button> <h4 class="modal-title" id="myModalLabel"> 新增用户信息 </h4> </div> <div class="modal-body"> @using (Html.BeginForm("UserAdd", "PhoneBook", FormMethod.Post)) { <div class="form-group"> <label>单位/姓名</label> @Html.TextBoxFor(c => c.UserInfo.Name, new { @class = "form-control input-sm" }) </div> <div class="form-group"> <label>电话</label> <div id="telNum" class="input-group"> @Html.TextBoxFor(c => c.Tel, new { @class = "form-control input-sm" }) <span class="input-group-btn"> <button id="addNum" class="btn btn-default btn-sm" type="button">+</button> </span> </div><!-- /input-group --> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal"> 关闭 </button> <button type="button" class="btn btn-primary"> 保存 </button> </div> } </div><!-- /.modal-content --> </div><!-- /.modal --> </div> </div> <script src="~/Scripts/jquery-1.9.1.min.js"></script> <script src="~/Scripts/bootstrap.min.js"></script> <script> $(document).ready(function () { var MaxInputs = 8; //maximum input boxes allowed var InputsWrapper = $("#telNum"); //Input boxes wrapper ID var AddButton = $("#addNum"); //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).after('<div id="telNum" class="input-group">@Html.TextBoxFor(c => c.Tel, new { @class = "form-control input-sm" })<span class="input-group-btn"><button id="removeNum" class="btn btn-default btn-sm" type="button">-</button></span></div>'); x++; //text box increment } return false; }); $("body").on("click", "#removeNum", function (e) { //user click on remove text if ( x > 1 ) { $(this).parent().parent('div').remove(); //获取当前元素的父元素的父元素的DIV并删除 x--; //decrement textbox } return false; }) }); </script> </body> </html>