【问题标题】:How do I add/remove text boxes with JQuery changing the variable name to keep the name attributes different?如何使用 JQuery 添加/删除文本框更改变量名称以保持名称属性不同?
【发布时间】:2015-12-15 08:41:59
【问题描述】:

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

例如,当我按下按钮添加作者时,会出现一个输入框,以便我可以添加作者姓名以及添加书籍的按钮,当我按下该按钮时,我会看到一个输入框以添加书籍名称.

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

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

我已经在图片中做到了这一点,但我得到了所有东西的数组。我希望它被作者分开。

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>

【问题讨论】:

  • 你的问题很混乱。能否请您对其进行编辑并使其易于理解。
  • @A.J 我添加了更多信息,我不知道这是否足以解释它。

标签: javascript jquery


【解决方案1】:

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

    <!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>

【讨论】:

  • 如何添加更多作者及其书籍author1 {book1, book2, book3} author2 {book4, book5} author3 {book6, book7, book8}
  • 如何将数据 arr 发送到数据库? @Divesh
  • 我一直在尝试将数组传递到 mysql 数据库中,但我似乎无法弄清楚这是否已完成。我已经尝试过 ajax,.click(),通过邮件发送它,但我不断收到错误
  • 没有看到你的代码我怎么能说你哪里出错了,发布你的代码[你如何发送数据。]
  • 增加了sendToServer函数,通过ajax函数sendToServer(data) { $.ajax({ type: "POST", data: { arr: JSON.stringify(data) }, url: "next.php", success: function(data) { alert(data); } }); }发送数据
【解决方案2】:

请尝试此代码并包含 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>

【讨论】:

    【解决方案3】:

    你可以试试这个....

    <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>
    

    【讨论】:

    • 如何保持书名与作者相同的编号,以便该书与该作者相关
    • 你不需要这样做。您可以通过选择 $('#books'+author number+'input').each(function(){alert(this.value);}) 来获取这些书籍
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-23
    • 2019-03-21
    • 2011-12-08
    • 1970-01-01
    • 2019-01-16
    • 2015-04-20
    • 1970-01-01
    相关资源
    最近更新 更多