jQuery: selecting the new HTML5 input elements with a custom selector

jQuery doesn't support the new HTML5 input types of form elements when it comes to custom CSS selectors. For that reason, we have to implement a custom jQuery selector that matches inputs such as email or url. Let's see how.

Here's our custom selector:

(function($) {
    var types = /text|search|number|email|datetime|datetime-local|date|month|week|time|tel|url|color|range/;
    $.extend($.expr[':'], {
        textall: function(elem) {
            var type = $(elem).attr('type');
            return types.test(type);
        }
    });
})(jQuery);

Our selector uses a regular expression against the value of the type attribute of each element. For example, given the following form:

<form action="#" method="post" id="form">
    <div>
        <input type="email" name="email" />
    </div>
    <div>
        <input type="date" name="date" />
    </div>
    <div>
        <input type="text" name="text" />
    </div>
    <div>
        <input type="checkbox" name="check" />
    </div>
    <div>
        <input type="radio" name="radio" />
    </div>
	<p><input type="submit" name="submit" value="Submit" /></p>
</form>
​

we can use the :textall selector as follows:

$('input:textall', '#form').addClass('text');​

You can see the demo below.

Demo

Live demo

Back to top