I am trying to pass a JSON element to a function, but it's not working. Any thoughts? Here is my code:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/smallbusiness/_assets/js/events.json",
success: formatJson,
error: function() {
alert("Data file failed to load");
}
});
});
function formatJson (data) {
var json = data.events.event;
var containerList = $('#event-list');
var containerDescrip = $('#event-descrip');
var template = '';
var defaultDescrip = '';
//Format and display event list
$.each(json, function(i, item) {
template += '<p><a href="javascript:void(0)" onClick="formatDescrip(' + i + ',' + json[i].title + ')">' + this.title + '</a></p>';
});
containerList.html(template);
}
function formatDescrip(j, jsonData) {
alert(j);
alert(jsonData);
}
I am trying to pass both i and json[i].title to formatDescrip() but it's throwing this error:
Error: missing ) after argument list
Source File: http://localhost/smallbusiness/webinars.html#
Line: 1, Column: 20
Source Code:
formatDescrip(3,How to Leverage Email Marketing)
What am I doing wrong? And what if I wanted to pass the entire json object? How would I go about that? It seems like it should be straightforward, but I keep getting errors.
formatDescrip(3,How to Leverage Email Marketing). This is not valid JavaScript. It should beformatDescrip(3,'How to Leverage Email Marketing')so you are missing quotation marks.javascript:void(0)theonclickattribute anymore in 2011... My eyes are bleeding.onclickeither...<a>has no href, then it shouldn't be a<a>anyway, use something else: a button or just a span. That way you don't have to worry about what to put in thehrefattribute. About theonclick, see the accepted answer or read more about theclickevent handler: api.jquery.com/click