DotNetCurry Logo

jQuery Input Control (TextBox) Performance Tips

Posted by: Suprotim Agarwal , on 6/6/2015, in Category jQuery and ASP.NET
Views: 20307
Abstract: Common Operations using jQuery Input (TextBox) control with performance tips

This recipe contains four most common operations you will be performing on the Input Text Box controls while working on your website or projects. Let us get started:

Getting and Setting a TextBox Value

The easiest way to select a single textbox element is to assign an ID to it:

<input type="text" id="txtBox" name="txtBox" />

You can then use jQuery’s selection function $("#txtBox") and can access the value of the TextBox using the val() method, with no arguments.

var tboxtext = $("#txtBox").val();

To set the text that appears in a textbox, use val(string)

$("#txtBox").val("some text");


Retrieving Multiple TextBox values

If you have a bunch of textboxes and want to get/set values on them, use map() or each() to traverse through all elements.

Create a HTML document named ‘InputMiscFunctions.html’ and use the following HTML markup:

      <input type="text" name="name" value="Suprotim" />
      <input type="text" name="location" value="Cloud9" />
      <input type="text" name="twitter" value="@suprotimagarwal" />
    <p id="status"></p>

We have a bunch of <input type="text"> elements here and a paragraph element. We will loop through these textboxes and print the values in the textbox using .map(). Write the following code in your <head> or before the closing <body> section of the page:

<script type="text/javascript">
    $(function () {
        var txtValues = $("input:text").map(function () {
            return $(this).val();
        }).get().join(", ");

$("input:text") allows us to select all <input type="text"> elements. map() iterates over the textbox elements and accepts a callback function. Although we haven’t specified any arguments in the callback function, map() can take up to two arguments: index of the current element and the element itself. this here refers to the current DOM element which is converted to a jQuery object using $(this) and we are using val() to access its value.

During each iteration, the function returns the value of the textbox and adds it to the object that the map() method returns. get() at the end gets the array object. join() is our regular Array.join function. It converts the array object to a string, putting the comma (,) between each element. Finally we use the append() method on the paragraph to print the textbox values.

Save the file and view it in your browser. Here’s the output:


Live Demo:


Detecting Events on a TextBox

In this example, we will detect whenever a Textbox on the page receives and loses focus. I have created a HTML page called ‘InputMiscFunctions.html’ and added the following markup:

    <input type="text" id="txtBox" name="txtBox" />
    <p id="status"></p>

Use the following code:

$(function () {
    var txt = $('input[type="text"]');
        .on('focusin', txt, function () {
            $("#status").text("Text box has focus!");
        .on('focusout', txt, function () {
            $("#status").text("Text box does not have focus!");

Here we are using the focusin and focusout events to detect when the textbox gains and loses focus respectively. focusin event is sent to an element when it, or any element inside of it, gains focus. Similarly the focusout event is sent to an element when it, or any element inside of it, loses focus.

Note: If we were interested in capturing events on the parent elements or during event bubbling, we could have used the focus and blur events. Since we do not have any such requirement, we are using focusin and focusout events.

Observe how we have used $('input[type="text"]') to select <input type="text"> element. Many a places you will also see $("input:text") being used to select the textbox. So which of the two approaches is better?

:text is a jQuery Pseudo-selector. Pseudo selectors look like CSS3 selectors but are not standardized. In large forms, Pseudo selectors can lead to slight performance issues, so it is wise to limit usage of pseudo-selectors only to the filter() function. The jQuery documentation recommends using [type="text"] for better performance in modern browsers as it makes use of the native DOM querySelectorAll() method. There are many other pseudo-selectors like :button to select button elements, :submit to select Submit buttons, :radio and :checkbox to select radiobuttons and checkboxes respectively. Use them wisely.

Live Demo: Controls/9.3-InputMiscFunctions.html


Disable and Enable a TextBox Programmatically

A textbox can be disabled very easily using:

$("#txtBox").prop('disabled', true);

To enable it again, use:

$("#txtBox").prop('disabled', false);

The same code works for a TextArea too. In case you are wondering why did I use prop() here instead of attr(), I have explained in my article Important Tips Every jQuery Developer Should Know that If you want to setup the default value for an HTML’s tag attribute, use attr(). However when you are setting properties on the window or document objects, you should always use prop(). Check the link I just shared to read more about it.

If you liked this article, take a look at a new jQuery book The Absolutely Awesome jQuery Cookbook which contains scores of practical jQuery/jQueryUI recipes you can use in your projects right away.

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on Google+
Further Reading - Articles You May Like!
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook

Page copy protected against web site content infringement 	by Copyscape

Feedback - Leave us some adulation, criticism and everything in between!