Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

zxywvu's avatar

jquery add dynamic html to div

I'm not sure if this would be the best option. But I want the option that when the user clicks a button, it will add another div.

HTML

<p>
    <a class="btn btn-lg btn-secondary me-2" id="addRealPerson">Real Person</a>
</p>

JS

<script>
    jQuery(function() {
        $(document).ready(function(){
            let count = 1;
            $('#addRealPerson').click(function () {
                count++;
                addRealPerson(count);
            });
            function addRealPerson(number) {
                let html = ''+
                    '<div class="col-lg-6 mb-3">\n'+
                    '<fieldset class="border p-2">\n'+
                    '<legend class="float-none w-auto p-2 h6 fs-6">Real Person</legend>\n'+
                    '<textarea name="real_person" id="real_person" class="form-control border-0" rows="10" aria-label="real_person"></textarea>\n'+
                    '</fieldset>\n'+
                    '</div>';
                $('#showRealPerson').append(html);
            }
        });
    });
</script>
0 likes
7 replies
Sinnbeck's avatar

That looks fine, but I would add prevent default to the click event so the a tag isn't treated like a link

$('#addRealPerson').click(function (e) {
    e.preventDefault() 
zxywvu's avatar

@Sinnbeck

I added your code to my codes, but it did not work

$('#addRealPerson').click(function (e) {
    e.preventDefault();
    count++;
    addRealPerson(count);
});

Please or to participate in this conversation.