Yuri Coelho
Yuri Coelho

Reputation: 11

JQuery Masked Input Does Not Working in Rails 6

I am trying to use the JQuery Masked Input in my form on Rails 6. But it seems to me that the application.js in assets is not working, i am not sure. I installed the plugin through yarn with the command: yarn add jquery-mask-plugin. It was included in package.json as a dependency.

To setup, I went to app/assets/javascripts/application.js. This is the file:

//= require jquery
//= require jquery_ujs
//= require jquery-mask-plugin
//= require_tree .

$.jMaskGlobals.watchDataMask = true;

In app/javascript/packs/application.js I tried to import the JQuery and the plugin ass well:

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require("jquery")
import 'inputmask';

Now in my form, this is how I tried to use the plugin:

<%= form.text_field :cpf, class:'form-control', 'data-mask': '999.999.999-99' %>

As I said before, I am not sure, but I think the problem is the application.js file in assets, cause I wrote a console.log("test") command just to see if it is executing and nothing appeared at the web console when the server was running.

Can someone would help me?

Upvotes: 1

Views: 1628

Answers (2)

Arslan Ahmad
Arslan Ahmad

Reputation: 21

  1. yarn add "jquery-mask-plugin"
  2. in app/javascript/packs/application.js

add require

require("jquery-mask-plugin")
  1. in app/javascript/packs/application.js

add line at the buttom

$.jMaskGlobals.watchDataMask = true;
  1. in .html.erb

    = d.text_field :phone_number, autocomplete: "phone Number", class: "form-control", placeholder: "03xx-xxxxxxx" , 'data-mask': '0000-0000000'

or in html.erb

<%= d.text_field :phone_number, autocomplete: "phone Number", class: "form-control", placeholder: "03xx-xxxxxxx" , 'data-mask': '0000-0000000' %>

Upvotes: 2

Bruno Alves
Bruno Alves

Reputation: 41

  1. in app/javascript/packs/application.js

    $(document).on('turbolinks:load', function () {
      var im = new Inputmask('999.999.999-99');
      var selector = $('#person_document');
      im.mask(selector);
    });
    
  2. yarn add inputmask

  3. in app/javascript/packs/application.js

    require('inputmask');
    
  4. in assets/javascript/application.js

    //= require jquery 
    //= require jquery_ujs 
    //= require jquery-mask-plugin 
    //= require_tree .  
    //= require jquery.inputmask.bundle.min
    $.jMaskGlobals.watchDataMask = true;
    
  5. in app/javascript/packs/application.js

    require('inputmask');
    

This solved the problem for me.

Upvotes: 1

Related Questions