Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger asp.net link button click on enter key press

I have 2 asp text boxes that I have attached jQuery to trigger linkbutton server side click if enter key is pressed on any of the 2 text boxes. But this does not seem to work, Please help me explain where and what I am doing wrong. I need a solution that works in all major browsers [IE7,8,9], [Firefox 3,4], Safari[4,5].

Here is my code,

<script language="javascript" type="text/javascript">
function GC_PostBack() {
    jQuery('#<%=lnkSubmitGiftCardNumber.ClientID%>').trigger("click");
}

and on server side pn Page_Load, I'm attaching this function to onkeypress event of textboxes.

 if (!IsPostBack)
    {
        txtGiftCardNumber.Attributes.Add("onkeypress", "if(window.event.keyCode == 13) { GC_PostBack(); }");
        txtGiftCardPin.Attributes.Add("onkeypress", "if(window.event.keyCode == 13) { GC_PostBack(); }");
    }

I have tried using .click() rather then .trigger("click"), but to no avail. Please help!

Thanks.

like image 232
Ashar Syed Avatar asked Apr 27 '11 20:04

Ashar Syed


1 Answers

Alison is correct, and if you wanted to use jQuery like you have, just do:

<script language="javascript" type="text/javascript">
    function GC_PostBack() {
        jQuery('#<%=lnkSubmitGiftCardNumber.ClientID%>').click();
    }
</script>

EDIT :

If you are using jQuery, why not use jQuery for all of this? Currently, what you have will not work cross-browser for the keypress event. I suggest something like this:

(function() {

    $('input[id$="txtGiftCardNumber"], input[id$="txtGiftCardPin"]')
        .keypress(function(e) {

            var keyCode;

            if (window.event) keyCode = window.event.keyCode;
            else if(e) keyCode = e.which;
            else return true;

            if (keyCode == 13) {

                $('[id$="lnkSubmitGiftCardNumber"]').click();
                return false;

            } else return true;

        });

});
like image 189
Code Maverick Avatar answered Sep 23 '22 18:09

Code Maverick