0

I currently have made a way so the user can add another text field to the form by pressing on a 'add_another' div, this uses basic JS so when the user presses on the div 'add_another' the div 'author_2' is toggled.

I would like to make it so that when the user presses on the 'add_another' div for a second time it shows 'author_3' div, and when they press 'add_another' again, it then shows 'author_4'. I have put all the CSS and HTML divs in place to support this, I am just trying to adapt my code so it shows one div after another, rather then toggling a single div.

Here is my JS:

<script>
    $(document).ready(function() {
        $('.add_another').on('click', function(){
            $('.author_2').toggle();
        });
    }); 
</script>

I have tried altering this code, however with no luck.

I haven't added my HTML as it is just 4 divs, 'author_1' 'author_2' ... 3...4

Thankyou for your help

cousbrad
  • 39
  • 7

2 Answers2

1

There are two solutions to Your problem.
First one - use static code
It means the max author count is 4 and if user gets to 4, this is it.
If so - You need to store the number of authors already shown.

        var authors_shown = 1;
        $(document).ready(function() {
            $('.add_another').on('click', function(){
                authors_shown++;
                if (!$('.author_'+authors_shown).is(":visible")) {
                   $('.author_'+authors_shown).toggle();
                }
            });
        }); 

But there is also a second - more dynamic option.
What if user wants to input 10 or 20 authors? You don't want to pre render all that html code and hide it. You should clone the div and change its id or if the (HTML) code (for another author) is not too long, you can render it within JS code.

    var div = document.getElementById('div_id'),
    clone = div.cloneNode(true); // true means clone all childNodes and all event handlers
    clone.id = "some_id";
    document.body.appendChild(clone);


If it's a form, then change names of input fields to array as author_firstname[]
Also You can store number of added authors in another hidden field (so you know how long to loop the form fields on the server side.
The second option is a bit more complex and longer, but way more dynamic.

Mike B
  • 2,756
  • 2
  • 16
  • 28
0

You should make another div when clicked on add_another: something like this:

<script>
    $(document).ready(function() {
        $('.add_another').on('click', function(){
            $('<div><input type="text" name="name[]" /></div>').appendTo('.your_container');
        });
    }); 
</script>

as you see, input's name has [] which means you should treat with the inputs as an array.

let me know if you got any further questions

good luck.