2017-02-13 43 views
4

你好,我有两个输入,当即时写入第一个输入时,与自动填写第二个输入字段中的密码jQuery功能。在键盘上用' - '替换空格

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

例如:

首先输入:你好世界,

第二个输入:你好世界

我有以下代码:

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

    val = $(this).val(); 

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

    $(".secondInput").val(val); 
}); 

回答

5

可能只需使用replace即可完成,如:

$(".secondInput").val($(this).val().replace(/ /g, "-")); 

注:我建议使用input,而不是keyup,因为当你跟踪用户输入的效率更高。

希望这会有所帮助。

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

 
<input class='firstInput' /> 
 
<input class='secondInput' />

0

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

 
    val = $(this).val(); 
 
    val = val.replace(/\s/g, '-'); 
 

 
    $(".secondInput").val(val); 
 
});

1

扎卡里亚Acharki一个衬垫是最少的代码量..但任何人都开始了它可能是非常难以把握。这是一个替代方案,对于初学者更容易遵循:

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

    //grab the text, note the use of the var keyword to prevent messing with the global scope 
    var input1 = $(this).val(); 

    // break the string into an array by splitting on the ' '. Then join the array into a string again with '-' as the glue 
    input1 = input1.split(' ').join('-'); 

    // or use regex, but regex is a whole other language: input1 = input1.replace(/ /g, "-") 

    //finally place the modified string into its destination 
    $(".secondInput").val(input1); 
});