Replace space ' ' by '-' on keyup
Asked Answered
A

3

5

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 );
});
Asymmetry answered 13/2, 2017 at 21:53 Comment(0)
L
8

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' />
Loaded answered 13/2, 2017 at 21:57 Comment(0)
F
2

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

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

    $(".secondInput").val( val );
});
Frodina answered 13/2, 2017 at 21:59 Comment(0)
F
2

Zakaria Acharki one liner is the least amount of code.. but for anyone starting out it might be pretty hard to grasp. Here is an alternative that is easier for beginners to follow:

$(".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 );
});
Fiery answered 13/2, 2017 at 22:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.