Veljko89
Veljko89

Reputation: 1953

javascript fire C# Click event

I need help here .. I have a bit o JS, Idea is that I allow user to log in using "Enter" keyboard ... now I did managed to check if "Enter" was clicked, but I am unable to figure out how to call my C# function ... I do understand JS is client side and my code is on server side, so I Should have some type of PostBack, but i can't figure it out to work on all browsers

This is a code I have so far ...

A button ...

 <asp:Button ID="Button2" CssClass="btn" runat="server" type="submit" Text="Sign in"
                    OnClick="btnSubmit_Click" />

And my js

$(document).keypress(function (e) {

    var target = document.getElementById("MainContent_Button2");

    if (e.which == 13) {
        __doPostBack('btnSubmit_Click', 'sender, null');

    }
});

Can you just point me toward right direction?

Upvotes: 1

Views: 501

Answers (1)

Ray Hogan
Ray Hogan

Reputation: 349

Why not just use Javascript to click the button?

document.getElementById('MainContent_Button2').click(); return false;

or if you're using jQuery

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

Try:

$(document).keypress(function (e) {

    var target = document.getElementById("MainContent_Button2");

    if (e.which == 13) {
        document.getElementById('MainContent_Button2').click(); return false;

    }
});

I haven't tested the above, but I've implemented something similiar countless times. I'd have a hidden button on the page and when the user hits the enter key I invoke the button click via JS.

Upvotes: 3

Related Questions