how to generate variable ids for html tags inside append function in jquery

- 1 answer

Ad

this is my code and i want to generate variable ids for the html tags inside the append function while the ids are generating outside where variables are declared but its not taking inside ..

  <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>jQuery Bind onclick Event to Dynamically added Elements</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    <script type="text/javascript" src="scriptj.js"></script>
    <script type="text/javascript">
        i=0;
        $(document).ready(function(){
            $("#add").click(function func(){
                ++i;
                console.log(i);
                var rem = 'remove' + i; //  here the ids are generating but they 
                var tblid = 'id' + i;   // not going inside append function
                var imgdiv = 'idiv' + i; 
                var imag = 'img' + i;
                $("#diva").append("<div id=tblid style='border:2px solid black; border-radius:5px;'><table align='right'><tr><td><a href='javascript:void(0);' id=rem >Delete</a></td></tr></table><table  align='center'><tr><td>Section Title</td><td><input type='textbox' size='160' /></td></tr><tr><td>Descrtiption</td><td><textarea rows='5' cols='162' style='border-radius:5px;'></textarea><td></tr></table><br>&nbsp &nbsp<input type='file' onchange='readURL(this);'/><div id=imgdiv style='border: 1px solid black'><img id=imag alt='your image' /></div></div><br>"); 
            });
            $(document).on("click", "a#rem" , function() {  
                $(this).parent().parent().parent().parent().parent().remove();  
            });
        }); 
    </script>
    </head> 
    <body>
        <table><tr><td><button id="add" style='border-radius:3px;'>Add Section</button></td></tr></table>
        <br>
        <div id="diva">

        </div>
    </body> 
    </html>  
Ad

Answer

Ad

You are not calling the variables in your code. They are being interpreted as string.

For example, in this part of your code:

 $("#diva").append("<div id=tblid style='border:2px solid black; ....

tblid is being considered as a string and not as a variable. You need to concatenate strings and variables, like so:

$("#diva").append("<div id=" +tblid+ " style='border:2px solid black; ...
Ad
source: stackoverflow.com
Ad