Koray Durudogan
Koray Durudogan

Reputation: 634

Select .net control by string containing in jquery

I am working in asp.net and I have two imagebuttons like this:

<asp:ImageButton runat="server" ID="Hosciz" ImageUrl="../image/ciz1.png" Width="20px"Height="20px" AlternateText="bla bla" />

<asp:ImageButton runat="server" ID="Hosciz2" ImageUrl="../image/ciz1.png" Width="20px"Height="20px" AlternateText="bla bla again" />

Like you see both imagebutton ids contains 'Hosciz' string so I wonder can I use an .each() function with id containing. I know there is something like

$("div[id*='Hosciz']").each(function(){.....});

Is there a way to do this with imagebuttons or other .net controls instead of a html control like div ? I mean there sould be, but how ?

I know I can solve this like

$("#<%=Hosciz.ClientID%>").click(function(){ 'do whatever you want' });

$("#<%=Hosciz2.ClientID%>").click(function(){ 'do whatever you want' });

but like said I just wonder if there is a way to do this with each() function ?

Upvotes: 2

Views: 29

Answers (1)

Phil Blackburn
Phil Blackburn

Reputation: 1067

Use a class attribute on the image:

<asp:ImageButton runat="server" CssClass="hosciz" ID="Hosciz" ImageUrl="../image/ciz1.png" Width="20px"Height="20px" AlternateText="bla bla" />
<asp:ImageButton runat="server" CssClass="hosciz" ID="Hosciz2" ImageUrl="../image/ciz1.png" Width="20px"Height="20px" AlternateText="bla bla again" />

and in jquery a class selector

$(".hosciz").each(function(){.....}); 

or

$("div.hosciz").each(function(){.....}); 

It has the added bonus of allowing you to a common style in css for the image.

Alternatively, use ClientIDMode="Static", to ensure your id in the html matches the asp ClisentID. This does of course come with other problems - you'll need to make certain the ID is unique, but comes with a performance boost in the html selectors.

<asp:ImageButton runat="server" ClientIDMode="Static"  ID="Hosciz" ImageUrl="../image/ciz1.png" Width="20px"Height="20px" AlternateText="bla bla" />
<asp:ImageButton runat="server" ClientIDMode="Static" ID="Hosciz2" ImageUrl="../image/ciz1.png" Width="20px"Height="20px" AlternateText="bla bla again" />

and in jquery,

$("#Hosciz, #Hosciz2").each(function(){.....}); 

Upvotes: 2

Related Questions