I am having an issue with accessing an attribute of an anchor with PrototypeJS 1.6.0.3.
My code below works when I hard-code the course_number variable, however I would like to be able to extract it from the anchor.
This is my anchor tag:
<a class="course_number_info_link" data-course-number="{$foo}" href="#">{$foo}</a>
This is my invoke method observing a click on the anchor:
$$('.course_number_info_link').invoke('observe', 'click', this.getCourseInfo(this));
This is my getCourseInfo
method, however the course_number
doesn't pull through. How can I get access to the data attribute?
getCourseInfo: function(element) {
var course_number = element.readAttribute('data-course-number');
console.log(course_number);
new Ajax.Updater('result-' + course_number, '/ajax/get_course_info.php', {
parameters: { course_no: course_number },
onSuccess: function(response) {
console.log(response);
}
});
}
the way you are setting up the observer is why it is failing - you are passing a complete function to the observer instead of the function reference
If this is ran inside of your object then this
is the object instead of the element
$$('.course_number_info_link').invoke('observe', 'click', this.getCourseInfo(this));
should be
$$('.course_number_info_link').invoke('observe', 'click', this.getCourseInfo);
the parameter that is passed into getCourseInfo()
will be an Event object not an element object - this
should be the element object or you can also get the element like this
getCourseInfo: function(event) {
var element = event.findElement();
var course_number = element.readAttribute('data-course-number');
//snip....