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 );
});
Use the String. replace() method to replace all spaces in a string, e.g. str. replace(/ /g, '+'); . The replace() method will return a new string with all spaces replaced by the provided replacement.
Use the String. replaceAll method to replace all spaces with underscores in a JavaScript string, e.g. string. replaceAll(' ', '_') . The replaceAll method returns a new string with all whitespace characters replaced by underscores.
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' />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With