How to get asp:button ID in jQuery

2019-08-07 11:53发布

问题:

I'm making .aspx file and using jQuery to do key press function. I made few <asp:Imagebutton> so write specific button id in jQuery part.

$(document).keypress(function (e) {
                if (e.which === 13) {
                    $("#ImageSave").click();
                }
            });

I wrote $("#ImageSave") following aspx button id. but asp:button id in html is different with my original button id. so I change jQuery code id part. $("#ImageSave").click(); to $("#MainContent_ImageSave"). But its click event is not fired.

asp.net

<asp:ImageButton ID="ImageSave" runat="server" imageurl="img/button_save.jpg"  
       AutoPostBack="True" onclick="ImageSave_Click" />    

html

<input name="ct100$MainContent$ImageSave" id="MainContent_ImageSave" 
     type="image" src="img/button_save.jpg" autopostback="True"></input>   

I think this problem because of using asp id in jQuery way is wrong. Would be nice if you can help me with this or atleast point me to the right direction :)

回答1:

You can use this as id

<%= ImageSave.ClientID %>

so instead of this

 $("#ImageSave").click();

use

 $("#<%= ImageSave.ClientID %>").click();

Or you can use ClientIDMode="Static" so that the id doesn't change at runtime. If you are using asp.net 4.0 and above.

<asp:ImageButton ID="ImageSave" runat="server" imageurl="img/button_save.jpg"  
   AutoPostBack="True" onclick="ImageSave_Click" ClientIDMode="Static" />