Reputation: 434
Trying to create dynamic JQUERY elements to get added to an HTML page. Would like to click on an event, create elements from an array and then the new elements go to different functions. So far I've got:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<head>
<title>Adding buttons dynamically to JQuery </title>
<link type = "text/css" rel="stylesheet" href="jquery-ui.css">
<script type = "text/javascript" src="jquery.min.js"></script>
<script type = "text/javascript" src="jquery-ui.min.js"></script>
</head>
<body>
<p>Firing off without a hitch, HTML page loaded properly</p>
<button id="classChoice">Show Classes</button>
<div id='classSection' style="margin:50px">This is our new section test
area</div>
<script type="text/javascript">
//Classes Array
var classesArray = [ 'Spanish','English','French'];
var classIndex = 0;
//Button functionality
var btn = document.getElementById('classChoice');
btn.addEventListener("click",click2Handler,false);
//Button handler
function click2Handler(){
alert('clicked button!'); /*Code to create variable for new button */
evaluator();
}
//Evaluator function
function evaluator()
{
if(classIndex<classesArray.length)
{//Only operate to the length of the classes array
for(var i = 0; i< classesArray.length;i++)
{
var whereCreated = jQuery('#classSection');//where to add
var id = 'btn' + classesArray[classIndex];
whereCreated.append('<br><button id="' + id + '">' + classesArray[classIndex] + '</button>');
jQuery('#'+id).button().click(function(){
alert('Dynamically added button: '+ id + ' has been clicked...going to selector function');alert('id of button clicked: ' + id);
selector(id);
});
console.log('whereCreated: '+whereCreated+". id: " +id);
classIndex++;
}
console.log('classIndex: ' + classIndex);
}
}
function selector(btnSelection)
{
switch(btnSelection)
{
case 'btnSpanish':
alert('Buenos Dias!'); break;
case 'btnEnglish':
alert('Howdy Partner!');break;
case 'btnFrench':
alert('Oui oui monsieur!');break;
default : alert('Unhandled exception inside selection');
break;
}
}
</script>
</body>
</html>
The problem is only the last button created has its id evaluated inside the selector function, in this case btnFrench. How do I get each button to pass the right ID?
Upvotes: 1
Views: 277
Reputation: 74420
You could create a closure:
(function (id) {
jQuery('#' + id).button().click(function () {
alert('Dynamically added button: ' + id + ' has been clicked...going to selector function');
alert('id of button clicked: ' + id);
selector(id);
});
})(id);
The closure defines a new scope. This is necessary because your handler isn't called until after the loop has finished, so i is not part of the scope at the time it is called, or (in some cases) has the last possible value from the loop. (src)
Upvotes: 2