how to generate variable ids for html tags inside append function in jquery
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>   <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
Related Questions
Ad
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad