自动格式化输入字段中输入的 10 位数字 phone

auto formatting 10 digits phone number as entered in the input field

在逻辑上是将 10 位数字 phone 自动格式化为以下格式 (xxx) 234-3456

<div class="field-group" style="align-items: center;">
    <div>
        <se-singleselect selected="{{phoneItem.phoneTypeId}}" fieldvalue="phoneTypeId" fieldname="name" desc="Phone Type" datasrc="{{_phoneTypes}}" id="phoneTypeSelect"></se-singleselect>
    </div>
    <div>
        <input type="text" id="phoneNumber" class="phone" name="phoneNumber" maxlength="14" placeholder="(xxx) xxx-xxxx" on-input="_allowNumbersCharsOnly" on-change="_formatPhoneNumber" value="{{phoneItem.phoneNumber::input}}">
    </div>
</div>

JavaScript 逻辑格式化


_formatPhoneNumber(digit) {
    let number = digit.target.value.replace(/[^\d]/g, '')
    if (number.length == 10) {
        number = number.replace(/(\d{3})(\d{3})(\d{4})/, "() -");
    }
    console.log(number) // (123) 456-6789
}

console.log 在控制台中显示正确的格式。

你试过换行吗

console.log(number)

Document.getElementById("phoneNumber").value = number

?

由于我在论坛的贡献很少,所以回复一个答案。

let phoneNumber = document.getElementById('phoneNumber');
phoneNumber.addEventListener('change',_formatPhoneNumber);
phoneNumber.addEventListener('keyup',_formatPhoneNumber);

function _formatPhoneNumber(evt) {
    let number = evt.target.value.replace(/[^\d]/g, '')
    if (number.length == 10) {
        number = number.replace(/(\d{3})(\d{3})(\d{4})/, "() -");
    }
    //console.log(number) // (123) 456-6789
    evt.target.value = number;
}
<div class="field-group" style="align-items: center;">
    <div>
        <se-singleselect selected="{{phoneItem.phoneTypeId}}" fieldvalue="phoneTypeId" fieldname="name" desc="Phone Type" datasrc="{{_phoneTypes}}" id="phoneTypeSelect"></se-singleselect>
    </div>
    <div>
        <input type="text" id="phoneNumber" class="phone" name="phoneNumber" maxlength="14" placeholder="(xxx) xxx-xxxx" on-input="_allowNumbersCharsOnly" on-change="_formatPhoneNumber" >
    </div>
</div>