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