doukengzi3517
doukengzi3517
2016-03-31 08:53

写入时更改输入字段值

已采纳

Let's say I have a input field

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

and do write something like this:

Hällo

Is it possible to check while writing if that field has a the letter ä and change it to an a while writing ?

So far, I built this:

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

$project = str_replace($search, $replace, $input);
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • douruobokui58233 douruobokui58233 5年前

    You don't do this with PHP, you would do it with 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);
        });
    });
    

    Add id="filename" to the input element for this to work. You can add as many letters to the replace array as you would like. You can also add more arrays to replace letters.

    https://jsfiddle.net/dek5as1x/1

    Edit: Solution for several letters

    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]);
            });
        });
    });
    

    Here you add a new array ([]) to replaces. Then you add all the letters to that array that should be turned into the same letter to that array. Example: ['ê','ë','è']. Then you add the letter to the replacewith array. It is important that the letter comes to replace the letters in the array has the same index as the corresponding array in replaces. This solution should be a little cleaner for when you have lots of letters to replace.

    点赞 评论 复制链接分享
  • dsafgdafgdf45345 dsafgdafgdf45345 5年前

    You can't do this using PHP because PHP is serverside.

    But you can do this using JavaScript. Try:

    <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()">
    
    点赞 评论 复制链接分享