We help IT Professionals succeed at work.

Only one word on <input

Medium Priority
Last Modified: 2013-11-19
Hi I have a form on one of my pages for entering in information such as names etc

I have some code that will make sure the first letter is always capitalised and the rest lowercase.
What I want to do is expand upon this and use substr to remove everything after the first space.
So if a user goes to enter in the first name field "John Smith" you would only get John

Below is current code
<input onblur="this.value = this.value.substr(0, 1).toUpperCase() + this.value.substr(1).toLowerCase();" type="text" name="last_name" value="lastname" size="10">

Open in new window

Watch Question

<input onblur="this.value = this.value.substr(0, 1).toUpperCase() + this.value.substr(1).toLowerCase(); this.value = this.value.split(' ')[0];" type="text" name="last_name" value="lastname" size="10">

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts

Would something like this work for you?
<script type="text/javascript">
function func(a){
	a = a.substr(0, 1).toUpperCase() + a.substr(1).toLowerCase();	
	a = a.split(' ')
	document.getElementById('test').value = a[0];
<input onblur="func(this.value);" type="text" name="last_name" value="lastname" size="10" id="test">

Open in new window


Try this also

<input onblur="this.value =this.value.substr(0, 1).toUpperCase() + this.value.substr(1).toLowerCase().substr(0,this.value.indexOf(' '));" type="text" name="last_name" value="lastname" size="10">


This works perfectly for what I was trying to achieve although the others have their merits this was first and easiest to implement
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.