阿塞拜疆号码的Javascript电话号码掩码

问题描述 投票:0回答:1

我一直在尝试在 WordPress FunnelKit 构建器结账中实现电话输入字段的代码片段,但当用户重新输入号码时,它无法按预期工作。我的目标是创建一种与此示例上的输入格式类似的输入格式,并进行一些修改。具体来说,我想修复字段开头的初始 0 数字,以便用户键入时,格式显示为:

(056)234-56-67

当他们继续输入时,0 数字应该在开头保持固定。下面是我之前添加到functions.php中的代码片段,但它没有完全实现预期的行为。您能否协助提供符合此格式的解决方案?

谢谢!

add_action( 'wp_footer', 'funnelkit_phone_mask' );

function funnelkit_phone_mask() {
   wc_enqueue_js( "
      $('#tel_no, #alt_tel_no')
      .keydown(function(e) {
         var key = e.which || e.charCode || e.keyCode || 0;
         var phone = $(this);
         // Don't allow anything but numbers and some control keys
         if (key !== 8 && key !== 9) {
           if (phone.val().length === 0) {
            phone.val('(' + phone.val()); // add opening bracket
           }
           if (phone.val().length === 4) {
            phone.val(phone.val() + ') '); // add closing bracket and space after area code
           }
           if (phone.val().length === 9) {
            phone.val(phone.val() + '-'); // add first hyphen after 3 digits
           }
           if (phone.val().length === 12) {
            phone.val(phone.val() + '-'); // add second hyphen after 2 more digits
           }
         }
         return (key == 8 || key == 9 || key == 46 || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
        });
   " );
}

// Function to set the placeholder and maxlength for both phone fields
add_action( 'wp_footer', 'funnelkit_phone_placeholder' );

function funnelkit_phone_placeholder() {
   wc_enqueue_js( "
      // Set placeholder and maxlength for tel_no field
      $('#tel_no').attr('placeholder', 'Tel. nömrəsi (___) ___-__-__');
      $('#tel_no').attr('maxlength', '15'); // Limit input to 15 characters

      // Set placeholder for alt_tel_no field
      $('#alt_tel_no').attr('placeholder', 'Alternativ tel. nomresi (___) ___-__-__');
      $('#alt_tel_no').attr('maxlength', '15'); // Limit input to 15 characters
   " );
}
javascript php wordpress encoding elementor
1个回答
0
投票

这样的事情可能会有所帮助;

  var code;

  window.onkeydown = function (e) {
    code = e.keyCode ? e.keyCode : e.which;
  };
  
  document.getElementById('organization_phone').addEventListener('input', function (e) {
    if(code !== 8){
    var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,2})(\d{0,2})/);
    e.target.value = '(' + x[1] + ') ' + x[2] + '-' + x[3] + '-' + x[4];
  }});
 <input type="text" id="organization_phone" name="organization_phone"  required placeholder="(056) 234-56-67" value="0">
 

© www.soinside.com 2019 - 2024. All rights reserved.