Search code examples
javascriptjqueryinputkeyup

Replace space ' ' by '-' on keyup


Hello i have two inputs and when im writing in the first input, with keyup jquery function im writing automatically in the second input field.

But I want to write line instead of space to the second input field when im clicking the spacebar.

For example:

First input: Hello world,

Second input: Hello-world

I have the following code:

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

    val = $(this).val();

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

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

Solution

  • That could be done simply using replace, like :

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

    NOTE : I suggest the use of input instead of keyup since it's more efficient when you track the user input.

    Hope this helps.

    $(".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' />