简体   繁体   中英

How can I add group of fields to my form every time user hits a button?

I'm using Bootstrap and I want to add a group of fields every time a user hits the "add" button. I wrote a part of javascript:

$(document).ready(function(){
    var i = 1;
    $("#add_row").click(function(){
        $('#singleCommercial' + i).html('...');
        $('#listOfCommercials').append('<div id="singleCommercial' + i + '"></div>');
        i++; 
        alert(i);
    });

    $("#delete_row").click(function() {
        if (i > 1) {
            $("#singleCommercial" + (i - 1)).html('');
            i--;
        }
    });
});

Every time when I hit the add button I get the popup with a proper value of 'i', but the fields are not added by itself. It works randomly for me - sometimes I need to add row, then delete it and then I can add two more rows, etc. Could you look at my fiddle: http://jsfiddle.net/7yd5o63q/ and tell me what's wrong and how can I add group of fields every time user hits a button? Thanks!

The element $('#singleCommercial' + i) does not exist when you try to set its HTML. Move that line below the next line where you add it do the document:

$('#listOfCommercials').append('<div id="singleCommercial' + i + '"></div>');
$('#singleCommercial' + i).html('...');

Here is a working updated version of your JSFiddle: http://jsfiddle.net/7yd5o63q/2/ .

Add your $('#singleCommercial'+i).html('...'); line AFTER the append. The problem here is that you are adding HTML to an element that doesn't exist yet. When you click the button again what was happening is that the previous i value's div was getting the HTML content for the next :-).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM