phone number rails js

365 views Asked by At

Is is possible to do this in rails. I have read about turbolinks. and have tried to adapt it for rails but was unable.

document.getElementById('phone').addEventListener('input', function (e) {
  var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
  e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
});
<input type="text" id="phone" placeholder="(555) 555-5555"/>

this code comes from: Mask US phone number string with JavaScript

1

There are 1 answers

1
Ajaykumar On

You can include the javascript code inside the Rails App, If you are gonna use this field in all over the application you can use this script in application.js in the folder app/assets/javascripts/application.js

document.getElementById('phone').addEventListener('input', function (e) {
  var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
  e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');

Include this in application.js

If you have page specific javascripts you can create a separate js file and include that in folder app/assets/javascripts