如何解决jQuery用«-»替换空格不适用于<input type =“ email” />
我无法使用«-»替换空白。为什么?
但是ein type =“ text”是有效的
我的代码HTML很简单:
<input type="text" class="demo" placeholder="type=text" /><br /><br />
<input type="email" class="demo" placeholder="type=email" />
我的代码jQuery:
$(document).on("keyup",".demo",function(e) {
$(this).val($(this).val().replace(/\s+$/g,"-"));
});
我的jsFiddle:
https://jsfiddle.net/6qo973vm/11/
解决方案?
解决方法
对于输入类型的电子邮件,返回的值文本始终会被修剪,因此您可以用所需的字符替换最后一个空格。
更新的小提琴here
摘要:
$(document).on("keyup",".demo",function (e) {
if (e.keyCode == 32) { // in case of space...
if (this.value.indexOf(' ') != -1) { // if the space is inside string
this.value = this.value.replace(/\s+/g,"-");
} else { // for type = email: the space is at the end: add a final char.....
this.value = this.value + '-';
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Replace whitespace by «-» Not workin in input type email</h1>
<input type="text" class="demo" placeholder="type=text"/><br/><br/>
<input type="email" class="demo" placeholder="type=email"/>
,
我还没有真正研究为什么这样的输入框具有这种行为。调试时,我还注意到event.target.value
在调用.val()
之前已被修剪。但是,请查看以下代码段,也许您可能会看到一些尚未发现的内容。还有一个延迟可能也需要修复。
$(document).on("keyup",function(e) {
if (this.id === "email") {
document.getElementById("email").value = document.getElementById("email").value.replace(" ","-")
} else {
$(this).val($(this).val().replace(/\s+$/g,"-"));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Replace whitespace by «-» Not workin in input type email</h1>
<input type="text" class="demo" placeholder="type=text" /><br /><br />
<input type="email" id="email" class="demo" placeholder="type=email" />
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。