ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming

jQuery for Web Designers: Dynamically Increase Your HTML Forms Fields As Website Visitors Type Into Them

Updated on July 6, 2011

What drives me crazy the most when entering information into web site forms is that my data gets cut off when I type and it gets hard for me to see what I am typing. I have to go back to the beginning of that form field.

Another problem is that when I type, sometimes the text gets cut off and I think I personally forgot to enter the beginning text. That is the nature of the beast with HTML forms and it has been like that for years.

Enter the benefits of jQuery: I developed some small jQuery code to make the HTML form inputs expand automatically when typing. Other webmasters have contacted me to ask me how I did that and I now offer it to you in this hub.

What this amazing little jQuery script will do:

Every time someone types into your HTML form, the input field will expand so your web site visitor will see all of their data every single time they type.

See below.

A regular ordinary HTML form

<html>

<head>
<title></title>
<style type="text/css">

.input
{
	width:50px;
}
</style>


</head>

 <BODY>

<form>
  Name <input class="input" name="name"/>
  Age <input class="input" name="age"/>
</form>


 </BODY>
</HTML>

This is just an HTML document with a form. Note the <form> tags. Also note how each <input> element has a class called "input" as in Name <input class="input" name="name"/>.

This class called input will be assigned to each form input element that you want to expand every time someone types.

The jQuery code:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function()
{

	var inputLength;
	var string;
	var currentLength;
	var currentLengthCss;

	$('.input').keyup(function()
	{
		
		string = $(this).val();
		inputLength = string.length;
		
		if(inputLength>6)
		{
			currentLength = $(this).css('width');
			currentLengthCss = parseInt(currentLength.replace("px",""));
			//window.alert(currentLength + "\n" + currentLengthCss);
			currentLengthCss += 12;
			$(this).css('width',currentLengthCss + "px");
		}
	});
	
});
</script>

My jQuery Variables

Explanation of this jQuery code:

Lines 6 to 9: I define my variables:

inputLength is the variable that will count the number of characters in the effected input field.

string is just what the web site visitor types into the input and will be used to define the value of the inputLength variable.

currentLength is also a variable that will be created from the css width property read back from the current input, also known as this.

currentLengthCss is the variable for the integer when we convert the css width property currentLength.


Explanation of the jQuery code

Line 11: $('.input').keyup(function()

I use a keyup event handler to capture the website visitors action of moving the key up, which means every single time they type a character into the input field. Remember that $('.input') is class name for each and every HTML input element in my form.

Line 14: I capture the actually data in the form into the variable string = $(this).val();

Line 15: I count the length of that string field.

Lines 17 to 24: This is where the real work begins. If my inputLength has higher than 6. You can use any hard integer for this depending on the default width of your input elements. This number will be different for every website.

In Line 19, we call for the css width property which will come back with the number of pixels as "px", but we need to perform some math with the number of pixels, so on line 20, I use a replace method to remove the "px" and wrap that whole thing inside a javascript parseInt function to make sure we get back a definite integer.

On lines 22 and 23, we add a hard integer like 12 (can be any number you'd like, but 12 works for me) to the current length returned by the CSS pixel number and then pop the "px" back onto the CSS.



Putting It All Together

<html>

<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<meta name="GENERATOR" content="Microsoft FrontPage 4.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
<title>Long Island Advancement of Small Business - small business training,
networking, seminars</title>
<style type="text/css">

.input
{
	width:50px;
}

<!--
.mmm {
	text-align: center;
}
.notice {
	font-family: Arial, Helvetica, sans-serif;
	text-align: center;
	font-weight: bold;
}
-->
</style>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function()
{

	var inputLength;
	var string;
	var currentLength;
	var currentLengthCss;

	$('.input').keyup(function()
	{
		
		string = $(this).val();
		inputLength = string.length;
		
		if(inputLength>6)
		{
			currentLength = $(this).css('width');
			currentLengthCss = parseInt(currentLength.replace("px",""));
			//window.alert(currentLength + "\n" + currentLengthCss);
			currentLengthCss += 12;
			$(this).css('width',currentLengthCss + "px");
			$('#message').text(currentLengthCss);
		}
	});
	
});
</script>


</head>

 <BODY>

<form>
  Name <input class="input" name="name"/><p/>

  Age <input class="input" name="age"/>
</form>


 </BODY>
</HTML>

In conclusion: Try It

This works. Simply copy and paste the code from Putting It All Together into your favorite HTML editor and try it out. Don't forget to change the hard integers to experiment.

You may notice that the inputs get exponentially larger as you type, but that is to be expected and is not a bug.

Comments

    0 of 8192 characters used
    Post Comment

    • hotwebideas profile image
      Author

      Bruce Chamoff 6 years ago from New York

      You're welcome, Andrew. Glad you like the article.

    • andrewwilliams63 profile image

      andrewwilliams63 6 years ago

      Very useful..thank you for this

    • hotwebideas profile image
      Author

      Bruce Chamoff 6 years ago from New York

      Thanks and you're welcome simcx.

    • profile image

      simcx 6 years ago

      Thanks for the tutorials :)

    • hotwebideas profile image
      Author

      Bruce Chamoff 6 years ago from New York

      Thanks, Blender. I have many more jQuery code samples comiing at you. I also have some PHP stuff coming soon as well.

    • blender profile image

      blender 6 years ago from Vancouver, BC

      I really like code samples with line by line explanation - you can learn so much!

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: "https://hubpages.com/privacy-policy#gdpr"

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)