Handy jQuery Code Snippets for Textboxes
Code snippets are great time savers as these are essentially just reusable pieces of code. Implementing client side validations can be done using jQuery, as well as some other basic tasks like clearing value or enabling and disabling textboxes. This post provides a list of useful jQuery code snippets for handling textbox related tasks with ease. These snippets are useful for validation, clearing out values on key stroke, copying one textbox value to another in real time and several other tasks. Check it out!
1. Clear input textbox value using ESC key
The ESC key is mainly used for cancelling your current process, closing popups, or clearing out input. If you wish to implement textbox value clearing when the ESC key is pressed, then following jQuery code will help you achieve this. It checks for the ASCII code of the key and if it matches with the ASCII code of the ESC key, then it simply clears the value of the textbox in focus. Like this:
$(document).ready(function() {   $('input[type="text"]').keyup(function(e){     if(e.keyCode == 27) {       $(this).val('');     }   }); });​
2. Clear input textbox on page load
Following jQuery code will clear all the input-type textboxes, when DOM is ready. It loops through all the textboxes present on the page and within the loop, clearing its value.
$(document).ready(function() {   $('input[type=text]').each(function() {     $(this).val(''); }); });​
If you want to clear the value of the event in focus, then use the following jQuery code:
$('input[type=text]').focus(function() { Â Â $(this).val(''); });
3. Allow only numbers in textbox
As part of some form validations, there may be a restriction that only allows numbers in the textboxes. For example, when the value represents age, price, number of days, etc. The following jQuery code will allow only numbers in the textbox with ID “txtNumberâ€. It uses the keydown event to detect the user input value’s ASCII code. In this case the ASCII code must be in a range of numbers. The following code allows keys like backspace for clearing the value and TAB keys for moving out of the textbox:
$(document).ready(function(){   $("#txtNumber").keydown(function(e)   {     if (e.shiftKey)       e.preventDefault();     else     {       var nKeyCode = e.keyCode;       if (nKeyCode == 8 || nKeyCode == 9) //Ignore Backspace and Tab         return;       if (nKeyCode < 95)       {         if (nKeyCode < 48 || nKeyCode > 57)           e.preventDefault();       }       else       {         if (nKeyCode < 96 || nKeyCode > 105)          e.preventDefault();       }     }   }); });
4. Disable Cut, Copy and Paste operation
The following jQuery code will disable ‘cut’, ‘copy’ and ‘paste’ operations on the input text boxes. Using the jQuery .on() method, the ‘cut’, ‘copy’ and ‘paste’ events are attached to all input text boxes and the code will prevent the default behavior, like this:
$(document).ready(function(){ Â $('input[type="text"]').on("cut copy paste",function(e) { Â Â Â e.preventDefault(); Â }); });
5. Set focus on the first textbox of the page
The following code will set the focus to the very first enabled input textbox on the page, when the page is originally loaded:
$(document).ready(function(){ Â $('input[type=text]:enabled:first').focus(); });
But if the very first textbox is not visible, for example if it is set to “display:none;†then the above code will fail. So the best solution is to check for visible and enabled textboxes and then set the focus. Like this:
$(document).ready(function(){ Â Â $('input[type=text]:visible:enabled:first').focus(); });
6. Turn off autocomplete for all textboxes
These days most modern browsers cache every single input and smartly houses a list based on the input, like a list of email addresses for an email address inbox. When you visit any website, the browsers will display a list of all previously used inputs. When this is not necessary for your work, it can be quite frustrating. If you wish to disable autocomplete for all textboxes present on the page, the following jQuery code will help:
$(document).ready(function(){  $('input[type="text"]').attr("autocomplete", "off"); })
Though you can set the autocomplete="off" attribute on textboxes, you will have to set it for all the text boxes and that takes time. Instead, use the single line of jQuery code and you can achieve the same for all the text boxes present on the page at once!
7. Copy value from one textbox to another while typing
If you wish to copy the content of one input textbox to another in real time, the following jQuery code will do the job. This jQuery code attaches a keyup event to the source and then assigns its value to the destination textbox:
$(document).ready(function() { Â Â $('#txtSource').keyup(function(e) { Â Â Â Â $('#txtDestination').val($(this).val()); Â Â }); });
The above code will copy the text from one textbox to another. But if you wish to sync multiple textboxes then assign a CSS class to every textbox which should be part of syncing and then bind the keyup event to the CSS class selector. The HTML code will look something like this:
<input type="text" id="txt1"/> <input type="text" id="txt2" />
Below is the jQuery code that binds the event to copyText and assigns the same value to all the elements that have copyText CSS class:
$(document).ready(function() { Â Â $('.copyText').keyup(function(e) { Â Â Â Â $('.copyText').val($(this).val()); Â Â }); });
8. Convert textbox value to uppercase
The following jQuery code will convert the textbox’s value to uppercase lettering when the focus goes out of the textbox. toUpperCase() is a JavaScript method which converts the string to upper case letters:
$(document).ready(function() { Â Â $('#txtSource').blur(function(e) { Â Â Â Â $(this).val($(this).val().toUpperCase()); Â Â }); });
You can also set to lower case using the toLowerCase() method. Like this:
$(this).val($(this).val().toLowerCase());
9. Change textbox width on focus and restore on focus out
The following jQuery code will change the textbox width to 350px and then restore again to 200px when the focus goes out. This code makes use of the jQuery animate method, which provides simple animation while changing width:
$(document).ready(function() { Â $('#txtValue').focus(function() { Â Â $(this).animate({ width: '300px'}, 'fast'); Â }); Â $('#txtValue').blur(function() { Â Â $(this).animate({ width: '200px'}, 'fast'); Â }); });
Using the animate() method, duration can be assessed. Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The default duration is 400 milliseconds. The strings 'fast' and 'slow' can be supplied to indicate durations of 200 and 600 milliseconds, respectively.
10. Disable all textboxes
The following jQuery code will disable all the textboxes present on the page by setting the "disabled" property to true:
$(document).ready(function() { Â Â $('input[type="text"]').prop("disabled", true); });
If there are multiple forms on your page and you wish to disable textboxes of a particular form, then all you need to do is supply the form Id to jQuery selector. Like this:
$(document).ready(function() { Â Â $('#frm1 input[type="text"]').prop("disabled", true); });
In this case, all the input textboxes for “frm1†will be disabled.
Conclusion
To sum up, these jQuery code snippets for input textboxes are handy when implementing validations, disabling and enabling, setting focus for providing a better user experience and, from a security point of view, to disable copying. These tiny snippets can save you valuable minutes, and allow you to complete tasks with ease!