I’m using jQuery Template to create a table of information. Each row contains a minus button, plus button, and a textbox between them. There is also some text. When you click the minus or plus button, a number in the textbox either goes up or down. All of this is dynamically rendered through the template, so how will my buttons work? I’ve tried the following as a test, and it just ends up calling the click function on all of my minusbutton elements:
jQuery('#template').tmpl(data).appendTo("#holdingCell");
jQuery('#holdingCell #minusbutton').click(
function(){
alert(this.id);
});
Here is the relevant pieces of my code. Does anyone have a suggestion on how I can make this work?
<script id="template" type="text/x-jquery-tmpl">
<div style="display:block;margin-bottom:20px;" id="${getNextId()}">
<div class="adjuster"><button id='minusbutton'>-</button><input id='quantityText' class="enterQuantity" type=text style="width:40px; margin-left:5px;margin-right:5px" /><button id=">+</button></div>
<div class="productName" style="width:200px"><div>${productname}</div></div>
<div class="quantity"><span style="font-weight:bold;">${quantity}</span><span> Remaining</span></div>
</div>
function getNextId(){
return id++;
}
function buildDialog(json){
//Stuff I didn't paste here turns the parameter 'json' into a variable 'data'
jQuery('#template').tmpl(data).appendTo("#holdingCell");
jQuery('#holdingCell #minusbutton').click(
function(){
alert(this.id);
});
You can change your template to add onclick to each button. Then pass in the parameter that you need to send to the function: