How to send a .js function from an asp.net button?

0

As I command to call a function of javascript from asp.net, I already did it of different forms, but it marks to me undefined, empty field, or it did not mark to me nothing and as far as I respect the form to do it is thus. / p>

Code to obtain value from a textbox.

var nick = $('#<%=txtNick.ClientID%>').text(); 
alert(nick);
var nick = $('#<%=txtNick.ClientID%>').val(); 
alert(nick);
var nick = document.getElementById("<%= txtNick.ClientID %>").value;

Textbox code:

<asp:TextBox ID="txtNick"
        runat="server"></asp:TextBox>

Button code that should activate the function.

 <asp:Button ID="btnEntrar" runat="server" Text="Entrar" OnClientClick="return autenticarme();" />
    
asked by David 24.03.2017 в 23:42
source

1 answer

1

Use OnClientClick :

<asp:Button ID="btnLlamaFuncionJS" runat="server" Text="Botón" OnClientClick="funcionJS()"/>

JavaScript Code:

function funcionJS() {
    //Código JavaScript
}

To get the value, use single quotes instead of double quotes:

var nick = document.getElementById('<%= txtNick.ClientID %>').value;

If you want to use jQuery, use the Id of the control directly:

var nick = $(".txtNick").val(); 

Update

I did a small exercise about your problem and I was able to get the contents of the text box and assign it to a just variable with the same code that I put at the beginning. The code of the ASPX file is as follows:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<script type="text/javascript">
    function autenticarme() {
        var nick = document.getElementById('<%= txtNick.ClientID %>').value;
        alert(nick);
        return true;
    }
</script>

<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="txtNick" runat="server"></asp:TextBox>
            <br /><br />
            <asp:Button ID="btnEntrar" runat="server" Text="Entrar" OnClientClick="return autenticarme();" />
        </div>
    </form>
</body>
</html>

The result is the following:

    
answered by 24.03.2017 / 23:45
source