【问题标题】:Changing input field value while writing写入时更改输入字段值
【发布时间】:2016-03-31 08:53:22
【问题描述】:

假设我有一个输入字段

<input type="text" class="form-control" name="filename">

然后写这样的东西:

你好

是否可以在写入时检查该字段是否有字母ä,并在写入时将其更改为a

到目前为止,我构建了这个:

$search  = array('ä', 'Ä');
$replace = array('ae', 'Ae');

$project = str_replace($search, $replace, $input);

【问题讨论】:

  • 是和不,你不能只使用 php,需要使用 jQuery / AJAX 才能工作,但是,我建议只使用 jQuery / JS,因为它是做你的电缆无需在用户每次写入字符时都执行 AJAX 调用。

标签: javascript php validation input str-replace


【解决方案1】:

你不用 PHP 来做这件事,你会用 Javascript 来做:

var el = document.getElementById("filename");
el.addEventListener('keyup', function(){
    var replace = ['ä','å'];
    var replacewith = 'a';
    var replace1 = ['ö'];
    var replacewith1 = 'o';
    replace.forEach(function(letter){
        el.value = el.value.replace(letter, replacewith);
    });
    replace1.forEach(function(letter){
        el.value = el.value.replace(letter, replacewith1);
    });
});

id="filename" 添加到输入元素以使其工作。您可以根据需要向替换数组中添加任意数量的字母。 您还可以添加更多数组来替换字母。

https://jsfiddle.net/dek5as1x/1

编辑:几个字母的解决方案

var el = document.getElementById("filename");
el.addEventListener('keyup', function(){
    var replaces = [['ä','å'],['ö','ø'],['ï','ì'],['ü','ù','û'],['ë','ê']];
    var replacewith = ['a','o','i','u','e'];
    replaces.forEach(function(letterGroup, index){
        letterGroup.forEach(function(letter){
            el.value = el.value.replace(letter, replacewith[index]);
        });
    });
});

在这里添加一个新数组 ([]) 来替换。然后将所有字母添加到该数组中,这些字母应转换为该数组中的相同字母。示例:['ê','ë','è']。然后将字母添加到 replacewith 数组中。重要的是字母来替换数组中的字母与替换中的相应数组具有相同的索引。 当您要替换大量字母时,此解决方案应该更简洁一些。

【讨论】:

  • 到目前为止,它工作得很好。您知道以更好的方式编写替换的解决方案吗?我有 10 个字母,我确实想更改这些字母,同时编写和链接这些变量看起来不太好。
【解决方案2】:

你不能用 PHP 做到这一点,因为 PHP 是服务器端的。

但是您可以使用 JavaScript 来做到这一点。 试试:

<script language="JavaScript">
function replace() {
var input = document.getElementById("filename");
input.value = input.value.replace("ä","a");
}
<script>

<input type="text" class="form-control" name="filename" onchange="replace()">

【讨论】:

    猜你喜欢
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    • 2019-01-18
    相关资源
    最近更新 更多