Issue with Jquery in plugin component

AI-generated summary

In a discussion about using jQuery in a Discourse plugin component, Luke_Clancy asked whether jQuery is automatically available and reported issues accessing DOM elements via jQuery in the init lifecycle hook. fzngagan clarified that init is too early — jQuery should be used in didRender or didInsertElement, and noted jQuery doesn’t need to be manually imported. Luke_Clancy confirmed didRender resolved the issue and explained the need for jQuery stemmed from a custom search requirement incompatible with HTML’s <datalist>. codinghorror advised against jQuery, noting its planned removal from Ember/Discourse within two years, recommending vanilla modern JS instead. In response, Luke_Clancy shared they’re now exploring Awesomplete as a jQuery-free alternative for autocomplete functionality. The thread highlights lifecycle timing, dependency management, and the broader shift away from jQuery in modern Ember/Discourse development.

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.

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.

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.

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