HOWTO · JavaScript

Javascript で Asp:TextBox の onextchanged イベントを起動する

JavaScript を介して asp:TextBox の ontextchanged イベントを発生させる方法は?

このページの内容

そうですね、Ajax やその他の方法でそれを実行したくない場合で、通常の ASP.NET ポストバックを楽しんでいる場合は、(他のライブラリを使用せずに)これを実行できます。

コードファイルで、C# および.NET 2.0 以降を使用している場合は、次のインターフェイスを Page クラスに追加して、次のようにします。

public partial class Default : System.Web.UI.Page, IPostBackEventHandler {}

次に、この関数をコードファイルに追加する必要があります。

public void RaisePostBackEvent(string eventArgument) {}

JavaScript の onclick イベントに次のコードを記述します。

var pageId = '<%=  Page.ClientID %>';
__doPostBack(pageId, argumentString);

次に、コードファイルは、JavaScript によって渡される String 引数として eventArgument 引数を使用して RaisePostBackEvent メソッドを呼び出します。これで、他の任意のイベントを呼び出すことができます。

これが問題の可能な解決策です。

WebForm1.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="textbox.WebForm1" %>

<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>

   <script type="text/javascript">
    function RefreshIt(selectObj) {
      __doPostBack('<%= Page.ClientID %>', selectObj.name);
    }
   </script>
<body>
  <form id="form1" runat="server">
  <div>
     <asp:TextBox runat="server" AutoPostBack="True" ID="txtG1" OnTextChanged="txtG1_TextChanged"
      onmouseout="javascript:RefreshIt(this);" ></asp:TextBox>
    <br />
    &nbsp;<asp:Label ID="Label1" runat="server" Font-Size="Large"></asp:Label>

  </div>
  </form>
</body>
</html>

ブラウザでコードを実行すると、次のような出力が得られます。

Javascript を介して Asp:TextBox の Ontextchanged イベントを起動します

入力フィールドにテキストを入力すると、ontextchange イベントがトリガーされ、次のような出力(つまり、赤色)が表示されます。

Javascript を介して Asp:TextBox の Ontextchanged イベントを起動します-ontextchange イベント

RefreshIt 関数を引数としてポストバックに変更できます。

背後で機能しているコードを理解し、ページに IPostBackEventHandler を追加して、RaisePostBackEvent 関数を処理する必要がある場合があります。

WebForm1.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace textbox {
  public partial class WebForm1 : System.Web.UI.Page, IPostBackEventHandler {
    protected void Page_Load(object sender, EventArgs e) {}

    public void RaisePostBackEvent(string Arg) {
      if (txtG1.ID == Arg)
        txtG1_TextChanged(txtG1, null);
    }

    protected void txtG1_TextChanged(object sender, EventArgs e) {
      Label1.Text = txtG1.Text;
      Label1.ForeColor = System.Drawing.Color.Red;
      Label1.BackColor = System.Drawing.Color.White;
    }
  }
}

次のコードを使用して、JavaScript を介して asp:TextBoxontextchanged() イベントを発生させることができます。