2

I have two Input fields I want to name based on user input but this name should be lowercase and spaces between words change to "-". I am doing like this

$(function() {
  $("#name").keyup(function() {
    var name = $("#name").val();
    var alias = name.charAt(0);
    $("#alias").val(alias);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input name="name" class="text-input medium-input" type="text" id="name" value="" />

<input name="alias" class="text-input medium-input" type="text" id="alias" />

This given me result I write "arslan" in first input field then showing "a" in second input field
Showing only one letter

2
  • 2
    You are using .charAt(0) thus getting first character. Can you share few inputs and expected outputs? Commented Feb 15, 2018 at 13:12
  • I want like this "Home services" then second input field make "home-services" Commented Feb 15, 2018 at 13:16

4 Answers 4

5

I want to name based on user input but this name should be lowercase and spaces between words change to "-".

Use replace

$("#alias").val( name.replace( /\s+/g, "-" ) );

Your function should look like

 $(function() {
     $("#name").keyup(function() {
        var name = $("#name").val();
        $("#alias").val( name.toLowerCase().replace( /\s+/g, "-" ) );
     });
  });
Sign up to request clarification or add additional context in comments.

6 Comments

And for conversion to lowercase, use : name.toLowerCase()
@ekqnp Thanks, I missed the same.
I think he wants .toLowerCase() as well.
@ekqnp, you got to it before my slow browser could submit, haha.
@adpro Happens to me all the time :)
|
1

You should copy the whole entry from name input to alias while replacing the spaces with '-' and turning it to lower case.

$("#name").keyup(function() {
  $("#alias").val($(this).val().replace(" ", "-").toLowerCase());
});

Comments

0

Simple Solution

var name = $("#name").val().toLowerCase();
var alias = name.split(" ").join("-");
$("#alias").val(alias);

Comments

0

This will help you

 $(function() {
      $("#name").keyup(function() {
       var name = $("#name").val().toLowerCase();
       $("#alias").val(name.replace(/-/g,' '));
     });
  });

The replace will change all - given in the name with space

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.