How to select an input element by its “name” attribute in jQuery

In this blog post I am discussing about about how we can use jQuery Attribute Equals Selector to select HTML input element by its “name” attribute.

You can do that as shown in following jQuery code:

//HTML
<input type="text" name="login" id="login" value="Login Id">
//jQuery Code
var inputText = $("input[name=login]").val();

The code shown above, used jQuery’s “Attribute Equals Selector”, you can read more about it in official jQuery documentation here: https://api.jquery.com/attribute-equals-selector/ 

Attribute Equals Selector, is not limited to only HTML input element or its “name” attribute. In fact it works with any attribute of all HTML elements.

In place of name attribute above, you can also use “type”, or any other attribute defined in HTML elements. You can even use “value” attribute to select elements using jQuery.

I have added few more examples below, which will show the uses of “Attribute Equals Selector” to understand it better. I am taking same HTML markup which I have used in start of the article.

We can select elements by its “value” attribute, as shown below:

var inputText = $("[value='Login Id']").val();

Note: In above code I have enclosed Login Id text in single quotes, it is required when you have space in between the text, if there is no space you can write it without single quotes. 

Or using “type” attribute as below:

var inputText = $("input[type=text]").val();

Note: In case we have multiple input elements with type=text, above code will select first element and return its value. 

Using “Attribute Equals Selector”, we can also combine multiple attributes to select an element, as shown below:

var inputText = $("input[type=text][name=login]”).val();

That is all about Attribute Equals Selector, but there are many other attributes selectors other than Equals.

You can read more about different types of Attribute Selector in official jQuery documentation here.  

One Response

Leave a Reply