Reputation: 149
Mega noob here so excuse me if this is a silly question or if it doesn't make any sense.
I have a li list which I create dynamically from a mySQL database. The code for this looks like this:
var resultCount = 0;
var mxKey = $.now();
$.get("\\php\\phpGenre.php?mxKey"+mxKey, function(genreData){
jsonResults = JSON.parse(genreData);
while (resultCount<jsonResults.length){
var genreName = jsonResults[resultCount]['genre_name'];
$('#genreList').append('<li><a href="#" onclick="searchGenres(' + genreName + ');return false"><span>' + genreName + '</span></a></li>');
resultCount++;
}
});
When I create my list I also need to be able to add an onClick event which calls a function... this function uses the list name as a value and is generated via the variable genreName. My list gets created ok but the onClick event doesn't work and keeps returning:
SCRIPT5009: 'Documentary' is undefined
or another example would be:
SCRIPT5009: 'Fantasy' is undefined
Where 'Documentary' and 'Fantasy' are the genreName.
So my question is how can I include an onClick event to each list item which will use the genreName as the value?
If I hard code the list it works fine:
<ul><li><a href="#" onclick="searchGenres('action');return false"><span>Still To Do...</span></a></li></ul>
Thanks.... sorry once again for my poor coding knowledge.
Upvotes: 1
Views: 4861
Reputation: 1074
Your html is being created as
searchGenres(Fantasy) or searchGenres(Documentary)
and so on. What you want is those parameters to be sent as strings. You can either change your code to look like
... searchGenres(\'' + genreName + '\') ....
Note the escape before one of the '. This will generate
searchGenres('Fantasy') or searchGenres('Documentary') and so on
IMO, a better option would be to use the jQuery functions to add events to fields after creating the html. See http://api.jquery.com/delegate/
Upvotes: 0
Reputation: 36000
Try this:
$('#genreList').append('<li><a href="#" onclick="searchGenres(\'' + genreName + '\');return false"><span>' + genreName + '</span></a></li>');
This will generate output:
<li><a href="#" onclick="searchGenres('action');return false"><span>action</span></a></li>
whereas your code generates:
<li><a href="#" onclick="searchGenres(action);return false"><span>action</span></a></li>
Upvotes: 1
Reputation: 36551
youu need to escape '
your genrename since u want to send it as string.
try this
$('#genreList').append('<li><a href="#" onclick="searchGenres(\'' + genreName + '\');return false"><span>' + genreName + '</span></a></li>');
Upvotes: 3