在keyup上替换''by' - '

Özk*_*kan 5 javascript jquery input keyup

你好我有两个输入,当我在第一个输入中写入时,使用keyup jquery函数im在第二个输入字段中自动写入.

但是当我点击空格键时,我想将行而不是空格写入第二个输入字段.

例如:

第一个输入:Hello world,

第二个输入:Hello-world

我有以下代码:

$(".firstInput").keyup(function(e) {

    val = $(this).val();

    if( e.keyCode == 32 ) {
        val += "-";
    }

    $(".secondInput").val( val );
});
Run Code Online (Sandbox Code Playgroud)

Zak*_*rki 6

这可以简单地使用replace,例如:

$(".secondInput").val( $(this).val().replace(/ /g, "-") );
Run Code Online (Sandbox Code Playgroud)

注意:我建议使用input而不是keyup因为它在跟踪用户输入时更有效.

希望这可以帮助.

$(".firstInput").on('input', function(e) {
  $(".secondInput").val( $(this).val().replace(/ /g, "-") );
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input class='firstInput' />
<input class='secondInput' />
Run Code Online (Sandbox Code Playgroud)