Why is the call to console.log(this.attr("id"));
ing up as undefined?
(function( $ ) {
$.fn.fs_suggest = function(options) {
console.log(this.attr("id"));
};
})( jQuery );
$("#places_search").fs_suggest();
Here is the HTML:
<div class="search_container" id="search">
<form data-remote="false" method="get" action="/search">
<input type="text" placeholder="search places" name="query" id="places_search">
<input type="submit" value="search">
</form>
</div>
I'm trying to get a reference to the element on which the .fs_suggest() function is called, in this case $("#places_search")
Why is the call to console.log(this.attr("id"));
ing up as undefined?
(function( $ ) {
$.fn.fs_suggest = function(options) {
console.log(this.attr("id"));
};
})( jQuery );
$("#places_search").fs_suggest();
Here is the HTML:
<div class="search_container" id="search">
<form data-remote="false" method="get" action="/search">
<input type="text" placeholder="search places" name="query" id="places_search">
<input type="submit" value="search">
</form>
</div>
I'm trying to get a reference to the element on which the .fs_suggest() function is called, in this case $("#places_search")
Share Improve this question edited May 16, 2012 at 2:30 botbot asked May 16, 2012 at 2:21 botbotbotbot 7,36914 gold badges61 silver badges96 bronze badges3 Answers
Reset to default 8I think you want this:
console.log($(this).attr("id"));
Unless I'm mistaken, this
refers to a DOM element (which doesn't have an attr
function), whereas $(this)
fetches the actual jQuery object (which does).
If this (or do I mean this
? hehehe...) doesn't work then you're simply calling the function on an incorrect selector.
Upon further perusal of the jQuery docs, it would appear that your problem lies elsewhere outside of the context you have provided us. Are you calling your plugin before the DOM has loaded properly? (e.g. outside of $(document).ready()
)
I am not 100% what is being produced by this notation:
$.fn.fs_suggest = function(options) {
...
But if $.fn
resolves to an Object and fs_suggest
is an property of that Object, then the this
inside the function would refer to that object and not a DOM element or jQuery wrapped element.
I have solved this. The problem was that I didn't place the call to fs_suggest() in a doc ready block. So the answer is to call it like this.
places.js.coffee:
$ ->
$("#places_search").fs_suggest()
and in another file the plugin:
(function( $ ) {
$.fn.fs_suggest = function(options) {
console.log(this.attr("id"));
};
})( jQuery );
now "this" will be seen, and will equate to $("#places_search").