Friday, May 13, 2022

[FIXED] How to append my HTML code into div correctly?

Issue

I have a problem in which when I append some elements (a table with two input type=text and a button) to a div tag, my elements move and go into the wrong place. My code:

<div id="tables"></div>
<script>
var HTML_new_group = '\
<h4>'+gpName+'</h4>\
<table border="1">\
    <thead>\
        <tr>\
            <td>option</td>\
            <td>value</td>\
        </tr>\
    </thead>\
    <tbody>\
        <tr>\
            <td><input type="text" class="np-gp-option" data-np-gp-option-id="'+gpId+'"></td>\
            <td><input type="text" class="np-gp-value" data-np-gp-value-id="'+gpId+'"></td>\
        </tr>\
        <input type="button" value="Add" class="np-gp-add" data-np-gp-add-id="'+gpId+'" />\
    </tbody>\
</table>';
$(HTML_new_group).appendTo("#tables");
</script>

Final code

Final view

As you can see, the button is at the top of the table


Solution

This is because you are appending an input in table without specifying the tr and td for it. See the last input that you have added. Wrap it in tr and a td it will be appended there in table.

var HTML_new_group = '\
<h4>'+gpName+'</h4>\
<table border="1">\
    <thead>\
        <tr>\
            <td>option</td>\
            <td>value</td>\
        </tr>\
    </thead>\
    <tbody>\
        <tr>\
            <td><input type="text" class="np-gp-option" data-np-gp-option-id="'+gpId+'"></td>\
            <td><input type="text" class="np-gp-value" data-np-gp-value-id="'+gpId+'"></td>\
        </tr>\
        <tr><td><input type="button" value="Add" class="np-gp-add" data-np-gp-add-id="'+gpId+'" /></td></tr>\
    </tbody>\
</table>';


Answered By - Majid Ali
Answer Checked By - Clifford M. (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.