Making name attribute selector case insensitive using jQuery

In this post I am going to explain, how we can make name attribute selector case-insensitive using jQuery. Let’s say we have a HTML markup like this:

<div id="parent">
    <input name="someinputName"></input>
    <input name="SOMEinputNAME"></input>
    <input name="someINputName"></input>
    <input name="someiNPutName"></input>
</div>

Now, we want to make the border color of all input textbox as red where the name attribute contains the word ‘input’. Now, we can achieve this using jQuery like this:

var $input = $('#parent input[name*="input"]');
$input.addClass('red');

The above code gets all the input elements inside the parent div with id `#parent` where the name attribute contains word ‘input’ and after that we simply add a class to it to get the desired ‘red border’ output. You can also view the demo example of it in the below fiddle.

Demo:  Working Demo on jsFiddle #1

But, as you can see in the above demo the name attribute contains selector is case-sensitive. Hence, only the first two inputs are set to class ‘red’, but what if we want to make that contain selector as case-insensitive and also not modify the existing contains selector functionality as it might be needed in other places. So, we will create our very own case-insensitive name attribute contains selector like:

// Creating a custom expression 
// for case insensitive name attribute contains selector
$.expr[':'].nameCaseInsensitive = function (node, stackIndex, properties) {
    return node.name.toLowerCase().indexOf(properties[3]) > -1 ;
};

// and use it here like
var $input = $('#parent input:nameCaseInsensitive("input")');
$input.addClass('red');

This will set the red border for all the inputs where the name attribute contains word ‘input’ no matter what’s the case of word input is. You can put this custom expression in your main master page js file or inside a utility class or in the same js file only inside the document ready() function at start so that it can be used in all the pages. You can also view the demo example of it in the below fiddle.

Demo:  Working Demo on jsFiddle #2

If you have any comments or suggestion about this post, I would really appreciate it.

Happy Coding 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s