【问题标题】:phone number rails js电话号码rails js
【发布时间】:2017-01-05 14:08:10
【问题描述】:

在 Rails 中可以做到这一点。我读过关于turbolinks的文章。并尝试将其调整为适用于轨道,但未能成功。

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"/>

此代码来自:Mask US phone number string with JavaScript

【问题讨论】:

    标签: javascript ruby-on-rails validation phone-number masking


    【解决方案1】:

    您可以在 Rails 应用程序中包含 javascript 代码,如果您要在整个应用程序中使用此字段,您可以在 application.js 中使用此脚本 在文件夹 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] : '');
    

    在 application.js 中包含这个

    如果您有特定于页面的 javascripts,您可以创建一个单独的 js 文件并将其包含在文件夹 app/assets/javascripts 中

    【讨论】:

    • 我把它放在 app/assets/javascripts 文件夹中,然后它应该可以工作了。我正在使用 form_for。我已经复制了html。我需要将 id 从“phone”更改为“venue_phone”并将“input”更改为“textarea”。 <div class="field"> <div class="form-text">Phone</div> <textarea class="form-control" rows="1.5" name="venue[phone]" id="venue_phone"> </textarea> </div>
    猜你喜欢
    • 2022-11-29
    • 1970-01-01
    • 2015-03-15
    • 2021-08-15
    • 2021-06-14
    • 2012-07-26
    • 1970-01-01
    • 2016-04-15
    • 1970-01-01
    相关资源
    最近更新 更多