gpt4 book ai didi

javascript - 获取函数以作为用户类型运行

转载 作者:行者123 更新时间:2023-11-29 23:51:21 25 4
gpt4 key购买 nike

我有一个电话号码输入,我试图让破折号在用户键入时出现在号码中。

我希望号码显示为 555-555-5555。

该函数在大部分情况下都有效,但只有在输入整数后才会输入破折号。我正在使用 keyup 函数,我认为它可以解决这个问题,但没有成功。

对于我必须做什么才能在用户输入数字时输入破折号有什么建议吗?

$('#phone').keyup(function() {
$(this).val($(this).val().replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<label class="contact-label">Phone Number:</label>
<input type="tel" class="contact_input" name="phone" id="phone">
</div>

最佳答案

我稍微修改了您的代码以生成一些我认为更容易阅读但仍能完成工作的内容。

我刚刚评估了 <input /> 的长度每个 .keyup() 上的标签值事件,然后相应地增加值。看看下面的代码片段:

--更新--

在对退格问题发表评论后,我添加了几行似乎可以解决问题的代码:

首先我检查了退格键或删除 .keyup()事件以防止格式化代码干扰更正数字中的错误。

我还添加了一些检查和全局 formatFlag变量以确保如果用户退格到像 3 或 6 这样笨拙的索引(通常会添加连字符),该格式将在下一个 .keyup() 恢复正常事件。

let formatFlag = false;

$(function(){

$('#phone').keyup(function(evt) {

let modifiedValue = $(this).val().replace(/-/g, "");

if(evt.keyCode == 8 || evt.keyCode == 46) { //8 == backspace; 46 == delete

//Checks whether the user backspaced to a hyphen index
if(modifiedValue.length === 3 || modifiedValue.length === 6) {

//Checks whether there is already a hyphen
if($(this).val().charAt($(this).val().length - 1) !== '-') {

formatFlag = true; //Sets the format flag so that hyphen is appended on next keyup()

} else {

return false; //Hyphen already present, no formatting necessary

}

} else {

formatFlag = false;

}

return false; //Return if backspace or delete is pressed to avoid awkward formatting
}

if(!!formatFlag) {

// This re-formats the number after the formatFlag has been set,
// appending a hyphen to the second last position in the string
$(this).val($(this).val().slice(0, $(this).val().length - 1) + '-' +
$(this).val().slice($(this).val().length - 1));

formatFlag = false; //Reset the formatFlag
}

if(modifiedValue.length % 3 == 0) {

if(modifiedValue.length === 0 || modifiedValue.length >= 9){

return false;

} else {

$(this).val($(this).val() + '-');
return;

}

}

});

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div>
<label class="contact-label">Phone Number:</label>
<input type="tel" class="contact_input" name="phone" id="phone" />
</div>

关于javascript - 获取函数以作为用户类型运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42724883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com