Balloon Fight
Balloon Fight

Reputation: 655

How to RestrictBlank Spaces In An Input Field In This Javascript?

I believe it's a new request from what I've seen here. I'm using onkeyup() on one input to append and create a new value in a second input. It works great but I want to restrict white/blank spaces in the second input. See pen here

HTML

 <input type="text" id="fullnames" onkeyup="createUsername();" placeholder="Enter Your Full Name">

<!--restrict blank space-->
<input type="text" id="username" placeholder="Username">

Script

    function createUsername() {
    var x = document.getElementById("fullnames").value;
    document.getElementById("username").value= x;
}

Final result

This is how it should be

Full Names : John Doe 
Username : johndoe

Upvotes: 0

Views: 86

Answers (2)

Martin Ad&#225;mek
Martin Ad&#225;mek

Reputation: 18429

You can use String.prototype.replace and String.prototype.toLowerCase methods:

var name = ' John Doe ';
var username = name.replace(/ /g, '').toLowerCase();

console.log(username);

Btw be aware that there can be more characters that you might want to handle too. For example in my language we can have those in name ěščřžýáíé (plus their upper case variants).

See this gist for more advanced way that can handle those (it does slightly different thing - putting dashes instead of spaces, but its almost the same):

https://gist.github.com/Majkl578/947036

Upvotes: 2

Teju
Teju

Reputation: 47

You could try this:

function createUsername() {
    var x = document.getElementById("fullnames").value;
    x = x.trim() // gets rid of leading and trailing spaces
    var username = document.getElementById("username");
    username.value = x;
}

Upvotes: 0

Related Questions