
This article illustrates some useful basic concepts that explain how it’s easy interacting with HTML forms using jQuery. I’ve prepared five practical step-by-step examples you can follow to learn quickly this argument. For a printable reference guide to the jQuery API I suggest you to download my jQuery Visual Cheat Sheet or take a look at the official jQuery documentation.
Simple characters counter
The first example is a simple character counter. Here is the result (try to write something into the input field below):
How can you implement it? Add an input field in your HTML document and a <span> tag for the counter in this way:
<input type="text" id="input-text"/><span id="count"></span>Then add this JavaScript code into the <head> tag of your page or into an external JavaScript file:
$(document).ready(function() {
$("input[id='input-text']").keyup(function count(){
counter = $("input[id='input-text']").val().length;
$("#count").html(counter);
});
});
The previous script, on keyup event, gets the value and the length of the string contained into the input field with ID="input-text" and updates the DOM element with ID="count" (in this case the <span> tag) using the jQuery attribute html().
Characters countdown
Now we can try to implement a simple variant of the previous example to realize a script that displays the number of remaining available characters in an input field. Here is the result (try to write something into the input field below):
The HTML code is exactly the same of the previous example. I only changed the id property for the input and span tags.
<input type="text" id="input-text-2"/> <span id="count-2"></span>Here is the JavaScript code that updates the counter:
$("input[id='input-text-2']").keyup(function countRemainingChars(){
maxchars = 10;
counter = $("input[id='input-text-2']").val().length;
if(counter==0){
$("#count-2").html(0 +" remaining chars")
} else {
$("#count-2").html(maxchars-counter+" remaining chars");
}
});In the code above I declared the variable maxchar to set the maximum number of allowed characters for the input field with id="input-text-2". On keyup event, the script gets the value and the length of the string contained into the input field with id="input-text-2" and updates the DOM element with ID="count-2” (in this case the <span> tag) with the difference between maxchars-counter or 0.
Basic form validation
This example illustrates how to implement a simple form validation. When the input element loses focus, an error message appears if the field is empty. Here is the result (try to select the input field and leave it blank):
Here is the HTML code:
<input type="text" id="input-text-3" maxlength="10" /><span id="msg"></span>And here is the JavaScript code:
$("input[id='input-text-3']").blur(function validate(){
el = $("input[id='input-text-3']");
inputString = el.val();
if(inputString==""){
el.css({
"background" : "red",
"color" : "white"
});
$("#msg").html("This field can't be empty!");
} else {
el.css({
"background" : "white",
"color" : "black",
});
}
});On blur event (when the input field loses focus), an error message appears if the field is empty and the background and text color of the input field change to red and white.
Pick values from a list
This example illustrates how it’s easy to add values into an input field picking them from a list. Here is the result (click on a list element, Smashing Magazine, Woork Up or Mashable):
Click on a website from the list:
- Smashing Magazine
- Woork Up
- Mashable
The HTML code to implement this example is not complex: I added an unordered list that contains the list of values you can pick:
<input type="text" id="input-text-4" size="40"/>
<ul id="values">
<li>Smashing Magazine</li>
<li>Woork Up</li>
<li>Mashable</li>
</ul>
And here is the JavaScript code:
$("ul[id='values'] li").click(function suggestValues(){
input = $("input[id='input-text-4']");
el = $(this).html();
$(this).remove();
newinput = input.val();
newinput = (newinput + el + ", ");
input.val(newinput);
});Naturally, this is a very basic example you can improve and customize how you prefer for your specific needs in your web projects.
Add elements into a list from a select field
This example illustrates how to add some value into an external list piking them from a select element. When you add a new element into the list, the selected option is contextually removed from the select element. I also added a nice fadeIn animation to improve the final effect.
Here is the HTML code:
<select id="my-list">
<option value="1">Smashing Magazine</option>
<option value="2">Woork Up</option>
<option value="3">Mashable</option>
</select>
<input type="button" id="submit-list" value="Button"/>
<ul id="selected-items-list"></ul>And here is the JavaScript code:
$("#submit-list").click(function selectItem(){
s = $("option:selected")
el = s.text();
destination = $("#selected-items-list");
$(destination).append('<li>'+el+'</li>');
$(destination +':last').css('display', 'none').fadeIn(1000);
$("option:selected").remove();
if($('#my-list option').length==0){
$('input[id=submit-list]').attr('disabled', 'disabled');
}
});When you pick an option from the select element, the option it’s added into the destination list with id=selected-items-list using .append(). To remove the option for the select element you can use .remove(). When the select is empty you can disable the button using .attr().
Conclusions
In this post we’ve started learning how to use jQuery to interact with HTML forms. Obviously all concepts illustrated are very simple but easy to learn and useful to start using quickly jQuery. If you are a developer I suggest you to download my jQuery 1.3 Visual Cheat Sheet. Comments and suggestions are appreciated.
by
Antonio Lupetti is an italian engineer, pro blogger, Mac user, founder of woorkup.com. He lives in Rome, Italy. Follow Antonio on 

October 14, 2009 at 3:50 pm
Great work, as usual :)
October 14, 2009 at 3:54 pm
Thanks!
October 14, 2009 at 4:02 pm
Niente su Mootools?
October 14, 2009 at 4:08 pm
Awesome! I have been looking for the count down type item so I can limit the characters in peoples usernames in blog posts, emails, ect. This has been added to delicious :)
October 15, 2009 at 12:18 am
great tutorials
thanks mate
October 15, 2009 at 12:30 am
Great tutorials!!!
October 15, 2009 at 1:38 am
Really nice way of presenting capabilities of jQuery. Good work, Antonio.
October 15, 2009 at 1:59 am
Antonio,
Thanks a lot for these tutorial series.
A doubt that I would like to clear is why did you use named function where you could’ve done the same with anonymous functions. For eg:
$("input[id='input-text']").keyup(function(){
counter = $("input[id='input-text']").val().length;
$("#count").html(counter);
});
});
October 15, 2009 at 3:18 am
Hello Antonio. I guess this code for the countdown counter is more accurate. Because when we write something in the box then delete it all, it gives me 0 remaining chars.
October 15, 2009 at 6:36 am
Nice post, just one comment, instead of
$("input[id='input-text-3']"doing$('#input-text-3')is the preferred way of calling an element by ID and is much faster.October 15, 2009 at 10:06 am
Great, I like this post, i will implements this lesson, especialy char count down on my website
October 15, 2009 at 1:29 pm
Great post, thanks for those valuable informations.
October 15, 2009 at 1:56 pm
Why do you use the attribute selector to get the input field with the correct id, rather than just the id selector? Much faster!
$(’#input-field’) is much faster than $(’input[id=input-field]‘)
October 15, 2009 at 2:05 pm
Yes it’s true. But in this post I used the attribute selector because I thought was simpler to understand for beginners.
October 15, 2009 at 6:32 pm
Good! I like this lesson series. I hope that I will get new series as soon as. Good job thankx
October 17, 2009 at 1:30 am
Hi here,
it’s a good tut !
Thanks for sharing your knowledges ;)
October 23, 2009 at 6:31 pm
I’m looking at the demos on Vista IE7 and they are not working, particularly the “basic form validation” demo. When I type something in, delete it and lose focus nothing happens. But in my FF it works. Is that something within the jquery code or my browser?
October 24, 2009 at 3:04 am
You can use $(this) in an event handler to refer to the element you are binding an event to, you don’t need to write out the selector again. (Very useful when you want to bind a function to multiple elements.)
October 25, 2009 at 6:43 am
Instead of keyup I would use keydown (if there exists that function)
November 7, 2009 at 1:14 am
this is so amazing stuff n pretty tidy n fast with jQuery