jquery add and remove input box

Code:

 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="js/jquery-3.3.1.min.js"></script>
<title>jquery无刷新添加和删除input输入框 增加减少input框</title>
</head>
<a href="#" id="AddMoreFileBox" class="btn btn-info">添加更多的input输入框</a>
<div id="InputsWrapper">
<div><input type="text" name="mytext[]" id="field_1" value="Text 1"/><a href="#" class="removeclass">&times;</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="#" class="removeclass">&times;</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>
</html>

effect:
Here Insert Picture Description

Published 14 original articles · won praise 2 · Views 811

Guess you like

Origin blog.csdn.net/breakaway_01/article/details/102636920