I wrote about jQuery wildcard selector syntax briefly back in 2009, and since then that post has received a lot of views – way more than a post that brief should ever have seen.
After seeing the number of views I did a quick bit of digging, and realised why I was having trouble back then, and possibly why the post has been viewed so often – it seems jQuery 1.3.2 dropped support for inline selector wildcards (i.e. \\S*), and there’s still posts, samples and examples lurking around encouraging people to use this old syntax.
What this means is that this will not work:
$('#content\\S*').each(function () {});
However this will:
$("div[id^='content']").each(function() {});
So once you know that things changed in 1.3.2 the syntax is pretty simple. To make things even simpler, here’s a couple of quick examples with some short explanations:
1. Match and Format fields which have “integer” in their id.
This matches all input fields that have the word integer somewhere in their ID, and then formats the value they contain. You’d find this useful if you’re needing to format data that’s created by an embedded/third party control on a page, or simply to format data in any instance where the elements have some standard naming going on.
$("*[class~='integer']").each(function () {
$(this).formatIntegerField($(this).val());
});
2. Apply a click handler to anything containing ‘btnNext’ in its id.
As the title says, this looks for anything with ‘btnNext’ in its id and applies the click handler. This is something that could be particularly useful for ASP.NET developers (either those working with 3.5 or lower, or who are working with 4.0 but are unable to use the static clientIDMode for whatever reason).
Using the snippet below would enable you to find ‘btnNext’ on the page regardless of whether it was embedded in a master page or in a user control (causing ASP.NET to modify the generated control ID, turning it into something similar to ctl00_Content_btnNext depending on the control hierarchy).
$("*[id$='btnNext']").click(function () {
// Do Magic here
});
Hope that helps someone!
Tags: jQuery, JavaScript
Posted on Friday, October 14, 2011 12:05 AM |