Is or is not simple, but need your help with this:
I need to dynamically create buttons and links in jQuery. Data loaded from XML is put in an array and now:
You might click on one of the buttons "category" "users" etc... it launches a function that should make a button for each of the categories f.ex.: lets make a function that will be launched by those buttons: it will search XML for with categoryID attr that contains txt with "something..." and will add it to #tester:
function clickedCat(cat){
alert("test btn" + cat); // to check if function started
// here just some script search 'cat' in XML etc...
})
}
now the function has to be triggered by the dynamically created buttons f.ex.:
function showCatName(){
$("#categories").html(" ");
for(i=0;i<catArr.length;i++){
qw = catIDArr[i];
$("<div id='showCatName"+qw+"'></div>").html("<input id='showCatName"+qw+"' type='button' title='showCatName"+qw+"' value='showCatName"+qw+"' />")
.click(function(event){clickedCat(qw)}).appendTo("#categories");
}
}
but the button created here has the same value for all of them - last qw that was loaded...
Q: How to make it remember the qw value - different for each btn ? so btn[0] launches qw[0], btn[1] launches qw[1] etc...
Second thing -same issue but i need to input that into html link :
function showCatName2(){
$("#categories").html(" ");
for(i=0;i<catArr.length;i++){
qw2 = catIDArr[i];
$("<div id='showCatName"+qw2+"'></div>")
.html("<a href='#' onclick:clickedCat("+qw2+")> Test btn"+qw2+"</a>")
.appendTo("#categories2");
}
}
onclick doesn't seem to work at all ...
Q1: How to make it work so it will dynamically create buttons that launch a function with different value ?
Q2: like above but istead of buttons i need to put it in link
Thank for help in advance, Lucas
You're having a closure problem with
showCatName()
. When you say this:You're binding a reference to
qw
to the function but this does not evaluateqw
. Theqw
variable is evaluated when the click handler is triggered and the value ofqw
will be what it had when the loop finished; all the click handlers will have the sameqw
value because, well, they all share the exact same variable. The usual solution to this is to forceqw
to be evaluated when building the click handler:You could use an immediately executing inlined function in place of
make_click()
but the above is probably clearer if you're having trouble with closures.Your second one does not work because
onclick:clickedCat
doesn't mean anything in HTML. Perhaps you meantonclick=clickedCat
. You'll probably run into quoting problems withqw2
with this approach.