jQuery Input Control (TextBox) Performance Tips

Posted by: Suprotim Agarwal , on 6/6/2015, in Category jQuery and ASP.NET
Views: 39047
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: http://www.jquerycookbook.com/demos/S2-InputControls/9.2-InputMiscFunctions.html


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: http://www.jquerycookbook.com/demos/S2-Input 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.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

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 The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn

Page copy protected against web site content infringement 	by Copyscape

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