¿Cómo puedo hacer un Postback de Cuadro de texto en KeyUp?


Tengo un cuadro de texto que cambia el contenido de un menú desplegable en el evento onTextChanged. Este evento parece dispararse cuando el cuadro de texto pierde el foco. ¿Cómo hago que esto suceda en el evento keypress o keyup?

Aquí hay un ejemplo de mi código

<asp:TextBox ID="Code" runat="server" AutoPostBack="true" OnTextChanged="Code_TextChanged">                

<asp:UpdatePanel ID="Update" runat="server">
    <ContentTemplate>
        <asp:DropDownList runat="server" ID="DateList" />             
    </ContentTemplate>
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="Code" />
    </Triggers>
</asp:UpdatePanel>

Así que en la parte posterior del código, enlazo el menú desplegable en la carga de la página. El evento Code_TextChanged simplemente vuelve a marcar el menú desplegable. Me gustaría que esto suceda en cada tecla en lugar de cuando el cuadro de texto pierde el foco.

Heredé esto código recientemente y este no es el método ideal de hacer esto para mí, pero las limitaciones de tiempo me impiden reescribir esto en un método web servicy.

He intentado usar jQuery para enlazar el evento "keyup" para que coincida con el evento "change" para el cuadro de texto, pero esto solo funciona en la primera tecla presionada.

Author: Russ Bradberry, 2009-11-18

4 answers

Esto resolverá su problema. La lógica es la misma que la solución sugerida por Kyle.

Echa un vistazo a esto.

<head runat="server">
<title></title>
<script type="text/javascript">
    function RefreshUpdatePanel() {
        __doPostBack('<%= Code.ClientID %>', '');
    };
</script>

    <asp:TextBox ID="Code" runat="server" onkeyup="RefreshUpdatePanel();" AutoPostBack="true" OnTextChanged="Code_TextChanged"></asp:TextBox>
    <asp:UpdatePanel ID="Update" runat="server">
        <ContentTemplate>
            <asp:DropDownList runat="server" ID="DateList" />
            <asp:TextBox runat="server" ID="CurrentTime" ></asp:TextBox>
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="Code" />
        </Triggers>
    </asp:UpdatePanel>

El código detrás va así...

 protected void Code_TextChanged(object sender, EventArgs e)
    {
        //Adding current time (minutes and seconds) into dropdownlist
        DateList.Items.Insert(0, new ListItem(DateTime.Now.ToString("mm:ss")));

        //Setting current time (minutes and seconds) into textbox
        CurrentTime.Text = DateTime.Now.ToString("mm:ss");
    }

He agregado un cuadro de texto adicional para ver el cambio en la acción, elimine el cuadro de texto.

 41
Author: CoderHawk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-16 12:29:50

Aquí hay una forma sencilla de hacerlo con javascript, un panel de actualización, gridview, sqldatasource y un cuadro de texto. A medida que escribe, busca en la tabla y muestra los resultados. Corto y dulce, sin código detrás.

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="test3.aspx.vb" Inherits="test3" %>

<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
 <script type="text/javascript">
     function runPostback() {
         document.forms["form1"].submit();
         document.getElementById("TextBox1").focus();
     }
     function getFocus(){
         var text = document.getElementById("TextBox1");
         if (text != null && text.value.length > 0) {
             if (text.createTextRange) {
                 var FieldRange = text.createTextRange();
                 FieldRange.moveStart('character', text.value.length); 
                 FieldRange.collapse();
            FieldRange.select(); } }
}

function SetDelay() {
    setTimeout("runPostback()", 200);
}




 </script>
</head>
<body onload="getFocus()">
<form id="form1" runat="server">
<div>
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="TextBox1" />
        </Triggers>
        <ContentTemplate>
            <asp:TextBox ID="TextBox1" onkeyup="SetDelay();" runat="server"></asp:TextBox>
            <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1">
            </asp:GridView>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:purchasing2ConnectionString %>"
                SelectCommand="SELECT [name] FROM [vendors] WHERE ([name] LIKE  @name + '%')">
                <SelectParameters>
                    <asp:ControlParameter ControlID="TextBox1" Name="name" PropertyName="Text" Type="String" />
                </SelectParameters>
            </asp:SqlDataSource>
        </ContentTemplate>
    </asp:UpdatePanel>
</div>
</form>

 4
Author: B Morgan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-04 19:47:59
 0
Author: Kyle Ballard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:54:29

Uso un truco de javascript para activar un evento onTextChanged, llamo a una función de desenfoque y luego reenfoco el texto de entrada (o, si tiene muchos texto de entrada, cambie el enfoque de dos texto de entrada)

Lo he probado en IE y Firefox.

Código Javascript:

function reFocus(id) 
    {
        document.getElementById(id).blur();
        document.getElementById(id).focus();
    }

Código Aspx

<asp:TextBox ID="txtProdottoLike" runat="server"
                ontextchanged="txtProdottoLike_TextChanged"
                onKeyUp="reFocus(this.id);" 
                AutoPostBack="True">
</asp:TextBox>

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>                
<asp:UpdatePanel ID="Update" runat="server">
    <ContentTemplate>
        <asp:GridView ID="GridProdotto" runat="server" AllowPaging="False" 
                AllowSorting="False" ForeColor="#333333" GridLines="None"
            OnSelectedIndexChanging="GridProdotto_SelectedIndexChanging"
            Visible="True"  Width="100%" Height="100%" AutoGenerateColumns="False">
            <RowStyle BackColor="WhiteSmoke" Font-Size="11px" />
            <AlternatingRowStyle BackColor="White" />
            <Columns>
                <asp:BoundField DataField="Prodotto">
                    <ItemStyle Width="80px" HorizontalAlign="Left" />
                    <HeaderStyle HorizontalAlign="Left" />
                </asp:BoundField>
                <asp:BoundField DataField="Descrizione">
                    <ItemStyle HorizontalAlign="Left" />
                    <HeaderStyle HorizontalAlign="Left" />
                </asp:BoundField>
                <asp:CommandField SelectText="Seleziona" ShowSelectButton="True" ItemStyle-HorizontalAlign="Right"></asp:CommandField>
            </Columns>
        </asp:GridView>
    </ContentTemplate>
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="txtProdottoLike" />
    </Triggers>
</asp:UpdatePanel>

La función de c# "GridProdotto_SelectedIndexChanging" recupera datos de la base de datos y construye la cuadrícula.

 0
Author: Albicocco,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-16 12:30:27