Issue with Jquery in plugin component

Is jQuery automatically enabled for plugin components? Am I missing a setup step?

I am having issues with simply accessing the html DOM through jquery (with the end goal of jquery’s autocomplete function). Here is an example of one of my attempts, attempting to retrieve the ID of an element using its id. It never finds the element. Its as if the javascript does not have a reference point.

---- in /src/plugins/test/assets/javascripts/discourse/components ----
---- element-main.js.es6 ----
import discourseComputed, { observes } from "discourse-common/utils/decorators";
import jQuery from 'jquery';

export default Ember.Component.extend({
  init() {
    this._super(...arguments);
    console.log("in the templates/components/element-main.js.es6");
    console.log(jQuery);
    const aaa = jQuery('#eleinp');
    console.log(aaa)
    console.log(aaa.attr('id'));
  }
});

---- in /src/plugins/test/assets/javascripts/discourse/templates/components ----
---- element-main.hbs ----
<p>element-main in temp</p>
<input id="eleinp" value="HAHAHA">

I tried this.element, $(this.element), $(this), $(), etc. as well.

1 Like

init is too early in the lifecycle to apply jquery. Also you don’t need to import it. Lastly, You need to evaluate if you REALLY need to use it in the first place. If you need to use it, didInsertElement or didRender are the correct places to use it.

3 Likes

Thank you! didRender() worked well, I also took out the redundant import statement. I am using jQuery as I have a custom search statement on input that does not mesh with the ‘datalist’ html element. This is as datalist only shows options when they explicitly contain a substring.

Try to avoid jQuery, it is going to be removed from Ember and thus Discourse within the next two years. Vanilla modern JS is sufficient.

5 Likes

Thanks for the heads up, I’m looking at Awesomplete instead of JQuery’s autocomplete now

2 Likes