jQuery Get Textbox ID Examples

In jQuery, Tips and Tricks by June 7th, 2012

3012 Views Be the first to Comment

Did you need to find out what the ID of a Textbox is using jQuery and do not know how to retrieve it? In this article, I am going to share with you a very simple way t use jQuery to get textbox ID. Actual code is just 1 line, so it’s super easy to follow and implement.

How to Get Textbox ID using jQuery

Let’s assume that you have 3 textboxes with ID “city”, “state” & “country”. The HTML code for the textboxes would be:

Now you want to get the ID of the textbox whose value has been changed.  You can do it in the following manner:

Example 1: Get Textbox ID on change in jQuery

When you run the above example, you will see the 3 input textbox. Simply enter anything in any of these boxes and click outside the box so that the textbox loses focus. As soon as you do that, you will see the JavaScript alert that shows you the ID of the textbox in which you just made the change.

Example 2 - Get Textbox ID using name attribute in jQuery

Let’s take the above example as the basis for this example. Let’s assume that you have only the name of the textbox and now you want to get the textbox ID using just the name, as soon as you click a button. For illustration purposes, let’s assume that you want to get the ID of the “country” textbox using just it’s name, when the “Get Country ID” button is clicked. You can do it as below:

In the above example, when you run the page, simply click on the “Get Country ID” button. You will receive a JavaScript alert box that gives you the ID of the “country” textbox. Note that we are using the “name” attribute of the “country” textbox in order to get it’s ID.

Example 3 - Get Textbox ID using class in jQuery

Let’s assume that you have applied a class of “my_state” to the State textbox. You can now find out the ID of this textbox when it’s value is changed, using the class like so:

When you run the above example, you will see the 3 input textbox. Simply enter anything in the State textbox and click outside the box so that the textbox loses focus. As soon as you do that, you will see the JavaScript alert that shows you the ID of the textbox in which you just made the change.

You can apply the same technique to multiple textboxes i.e. apply the same class to any other textbox you may have in the page. As soon as you enter something in the textbox and click outside it, it will alert the ID of that textbox.

That’s it!

Do you know of any other ways to get textbox ID using jQuery? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*