在keyup上替换''by' - '

时间:2017-02-13 21:53:45

标签: javascript jquery input keyup

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

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

例如:

  

首先输入:Hello world,

     

第二个输入:Hello-world

我有以下代码:

public class DieTester2
{
    public static void main(String[] args) 
    {

        Die die1 = new Die();
        Die die2 = new Die();

        die1.setSides(6);
        die2.setSides(6);

        die1.roll();
        System.out.println("Die 1: " + die1.getValue());

        die2.roll();
        System.out.println("Die 2: " + die2.getValue());

        int sum = (die1.getValue() + die2.getValue());
        System.out.println("Sum: " + sum);

        if(die1.getValue() == die2.getValue())
        {
        System.out.println(getMessage(sum));
        }
}
        public static String getMessage(int sum) {

            String message;

            switch (sum)
            {

                case 2:
                message = "Snake Eyes!";
                break;

                case 4:
                message = "Four, the hard way!";
                break;

                case 6:
                message = "Hard Six!";
                break;

                case 8:
                message = "Eight, the hard way!";
                break;

                case 10:
                message = "Hard Ten";
                break;

                case 12:
                message = "Box Cars!";
                break;

                default:
                message = "Something went wrong";
                break;

           }

           return message;

        }
    }
}

3 个答案:

答案 0 :(得分:6)

只需使用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' />
&#13;
&#13;
&#13;

答案 1 :(得分:2)

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

答案 2 :(得分:1)

&#13;
&#13;
$(".firstInput").keyup(function(e) {

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

    $(".secondInput").val( val );
});
&#13;
&#13;
&#13;