如何使用JQuery添加/删除文本框更改变量名称以保持名称属性不同?

时间:2015-12-15 08:42:00

标签: javascript jquery

我想用JQuery创建一个图书目录,以便为作者添加图书。在我所拥有的代码中,我试图添加一个作者,并将他的书放在一个只有他的数字的数组中。由其他作者和他们自己的书籍分开。

例如,当我按下按钮添加作者时,会出现一个输入框,这样我就可以添加作者姓名按钮来添加一本书,当我按下该按钮时,我会得到一个输入框来添加书名。

ex1

当我再次按添加作者时,我希望能够添加与之前相同的输入框的另一位作者(向该作者添加更多书籍)。

ex2

还要添加分配给该作者的多本书。

enter image description here

我已经在照片中完成了这个,但我得到了一系列的东西。我希望它被作者分开。

author1有一个{book1,book2,book3 ...}

的数组

author2的数组为{book13,book14,book15}

(我是JQuery的初学者)

这是我到目前为止的代码:

<!DOCTYPE html>
<html>
<head>
<title>Add or Remove text boxes with jQuery</title>
<script type="text/javascript" src="//code.jquery.com/jquery-latest.js"></script>
<style type="text/css">
<!--
#main {
    max-width: 800px;
    margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
    <h1>Add or Remove text boxes with jQuery</h1>
    <div class="my-form">
        <form role="form" method="post">
            <p class="all_fields">

                <button class="add_author">Add Author</button>

                <div id="commonPart" class="commonPart">
                    <label for="author1">Author <span class="author-number">1</span></label>            
                    <br/>
                    <input type="text" name="author" value="" id="author1" />
                    <br/>
                    <button class="add_book">Add book</button>
                    <div>
                        <input type="text" class="bookName" name="authBook[]"/>
                    </div>
                </div>
            </p>
            <p><input type="submit" value="Submit" /></p>
        </form>
    </div>
</div>

<script type="text/javascript">

$(document).ready(function($){
    var wrapper         = $(".all_fields"); //Fields wrapper
    var commonPart      = $("#commonPart"); 
    var add_author      = $(".add_author"); //Add button ID
    var add_subButton   = $(".add_book"); //Add sub button ID
    $('.my-form .add-box').click(function(){

        var n = $('.all_fields').length + 1;
        if( 15 < n ) {
            alert('Stop it!');
            return false;
        }


    $(add_author).click(function(e){
       e.preventDefault();
        var htmlToAdd = $('<label for="author' + n + '">Author <span class="author-number">' + n + '</span></label><br/><input type="text" name="author' + n + '" value="" id="author' + n + '" /><br/><button class="add_book">Add book</button><a class="add-book" href="#">Add Book</a><div><input type="text" class="bookName" name="authBook' + n + '[]"/></div>');
        htmlToAdd.hide();
        $('.my-form p.all_fields:last').after(htmlToAdd);
        box_html.fadeIn('slow');
        return false;
    });

    $(add_book).click(function(e){
       e.preventDefault();
        var htmlToAdd = $('<div><input type="text" class="bookName" name="authBook' + n + '[]"/></div>');
        htmlToAdd.hide();
        $('.my-form p.all_fields:last').after(htmlToAdd);
        box_html.fadeIn('slow');
        return false;
    });

    $('.my-form').on('click', '.remove-box', function(){
        $(this).parent().css( 'background-color', '#FF6C6C' );
        $(this).parent().fadeOut("slow", function() {
            $(this).remove();
            $('.box-number').each(function(index){
                $(this).text( index + 1 );
            });
        });
        return false;
    });
});
</script>
</body>
</html>

3 个答案:

答案 0 :(得分:2)

更新了代码(修复了一些错误..),试试这个......

    <!DOCTYPE html>
    	<html>
    		<head>
    			<title>Add or Remove text boxes with jQuery</title>
    			<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    			<style type="text/css">
    				<!--
    				#main {
    					max-width: 800px;
    					margin: 0 auto;
    				}
    				-->
    			</style>
    		</head>
    		<body>
    			<div id="main">
    				<h1>Add or Remove text boxes with jQuery</h1>
    				<div class="my-form">
    					<button onclick="addAuthor()" >Add Author</button><br><br>
    					<div id="addAuth"></div>
    					<br><br>
    					<button onclick="submit()" >Submit</button>
    				</div>
    				
    				<div id="result" ></div>
    			</div>
    			
    			<script type="text/javascript">
    				var authors = 0;
    				function addAuthor(){
    					authors++;
    					var str = '<div id="auth'+authors+'"><input type="text" name="author" id="author'+authors+'" />'
    								+'<button onclick="addMore(\'auth'+authors+'\')" >Add Book</button>'
    								+'</div>';
    					$("#addAuth").append(str);
    				}
    				
    				var count=0;
    				function addMore(id){
    					count++;
    					var str = '<div id="bookDiv'+count+'">'
    							+'<input class="'+id+'" type="text" name="book'+id+'" />'
    							+'<span onclick="addMore(\''+id+'\')" style="font-size: 20px; background-color: green; cursor:pointer;">+</span>'
    							+'<span onclick="removeDiv(\'bookDiv'+count+'\')" style="font-size: 20px; background-color: red; cursor:pointer; margin-left:1%;">-</span>'
    							+'</div>';
    					$("#"+id).append(str);
    				}
    				
    				function removeDiv(id){
    					var val = confirm("Are you sure ..?");
    					if(val){
    						$("#"+id).slideUp(function(){$("#"+id).remove();});
    					}
    				}
    				
    				function submit(){
    					var arr = [];
    					for(i=1; i<=authors; i++){
    						var obj = {};
    						obj.name = $("#author"+i).val();
    						obj.books = [];
    						$(".auth"+i).each(function(){
    							var data = $(this).val();
    							obj.books.push(data);
    						});
    						
    						arr.push(obj);
    					}
    					
    					$("#result").html(JSON.stringify(arr));
    				}
    			</script>
    		</body>
    	</html>

答案 1 :(得分:0)

请尝试此代码并包含jquery min js:

<div class="my-form">
    <form role="form" method="post">
        <p class="all_fields">



            <div id="commonPart" class="commonPart">
                <label for="author1">Author <span class="author-number"></span></label>            

                <input type="text" name="author" value="" id="author1" />
                <br/>

                <div>
                    <label for="author1">book <span class="author-number"></span></label>      
                    <input type="text" class="bookName" name="authBook[]"/>
                </div>

            </div>
        <button type="button" class="add_author" onclick="AddCustomMOre();">Add More</button>

        </p>
        <p><input type="submit" value="Submit" /></p>
    </form>
</div>
   <script> function AddCustomMOre(){
   $(".all_fields ").append('<div id="commonPart" class="commonPart"><label for="author1">Author <span class="author-number"></span></label> <input type="text" name="author" value="" id="author1" /> <br/> <div><label for="author1">book <span class="author-number"></span></label>  <input type="text" class="bookName" name="authBook[]"/></div>   <a href="javascript:void(0)" onclick="$(this).parent().remove();">Remove</a></div>');  
} </script>

答案 2 :(得分:0)

你可以尝试这个......

<p class="all_fields">

    <button class="add_author">Add Author</button>

  <div class="commonPart">
    <label for="author1">Author <span class="author-number">1</span></label>            
    <br/>
    <input type="text" name="author1" value="" id="author1" />
    <br/>
    <button div-id="1" class="add_book">Add book</button>
    <div id="books1">
        <input type="text" class="bookName" name="authBook[]"/>
    </div>
  </div>
</p>

<script>
    var c=1;
    $(".add_author").on("click",function(){
        c++;
        $(".all_fields").append('<div class="commonPart"><label for="author'+c+'">Author <span class="author-number">'+c+'</span></label><br/><input type="text" name="author'+c+'" value="" id="author'+c+'" /><br/><button class="add_book" div-id="'+c+'">Add book</button><div id="books'+c+'"><input type="text" class="bookName" name="authBook[]"/></div></div>');
    });
    $(".add_book").on("click",function(){
        var id=$(this).attr("div-id");
        $("#books"+id).append('<input type="text" class="bookName" name="authBook[]"/>');
    });
</script>