I have a click function that works for one of my anchor tags but I want it to work for two (or more). When I click on the anchor with id get-data-1 it displays the json file microLesson1.json for the div with class quiz-list-1. I want it to display the json file microLesson2.json when I click on the anchor with id get-data-2 as well. <!DOCTYPE html> <html> <head> <title>Test</title> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> <style> table.my-new-list { width: 20%; } </style> </head> <body> <a href="#" id="get-data-1">MicroLesson 1</a><br /> <a href="#" id="get-data-2">MicroLesson 2</a> <div class="quiz-list-1"></div> <div class="quiz-list-2"></div> <script> $(document).ready(function() { $('#get-data-1').click(function () { $.getJSON( "ajax/microLesson1.json", function( data ) { var items = []; $.each( data, function( key, val ) { items.push( "<tr><td>" + key + "</td><td>" + val + "</td></tr>" ); }); $( "<table />", { "class": "my-new-list", html: items.join( "" ), }).appendTo( ".quiz-list-1" ); }); }); }); </script> </body> </html> Code (markup): microLesson1.json { "Quiz 1": "80%", "Quiz 2": "100%", "Quiz 3": "90%" } Code (markup): microLesson2.json { "Quiz 1": "70%", "Quiz 2": "50%", "Quiz 3": "90%", "Quiz 3": "80%", "Quiz 3": "60%" } Code (markup):
Add a class, trigger the click on the class, fetch the ID of the clicked element, extract the number, add that number dynamically to the json-call, and presto Something like this should do the trick <body> <a href="#" id="get-data-1" class="fetchjson">MicroLesson 1</a><br /> <a href="#" id="get-data-2" class="fetchjson">MicroLesson 2</a> <div class="quiz-list-1"></div> <div class="quiz-list-2"></div> <script> $(document).ready(function() { $('.fetchjson').click(function () { var idNumber = $(this).attr('id').split('-').reverse()[0]; $.getJSON( "ajax/microLesson"+idNumber+".json", function( data ) { var items = []; $.each( data, function( key, val ) { items.push( "<tr><td>" + key + "</td><td>" + val + "</td></tr>" ); }); $( "<table />", { "class": "my-new-list", html: items.join( "" ), }).appendTo( ".quiz-list-"+idNumber+"" ); }); }); }); </script> Code (markup):
Thanks for the code, PoPSICLe. It only gets the first microLesson1.json file. Even when I hard code the idNumber as 2 it just displays the first json file.
I tried it again and it only accepts idNumber equal to 1. When I set idNumber equal to 2 nothing happens.
When I put the microlesson anchor for 2 on top of the one for 1 it does work. So the order just has to be changed.