2011-04-26 54 views
5

我有一个文本框asp.net服务器控件。我正在修改JavaScript的文本框的值,我想要检测文本框文本何时更改。我尝试了onchange事件,当文本改变时它会被丢失。但在我的情况下,我从Javascript中更改文本。我怎么能做到这一点?如何从javascript中检测文本框更改事件

回答

6

更新value属性不会触发更改事件。更改事件由用户触发。

你可以写从而改变价值和做你需要做其他的功能......

function changeTextarea(str) { 
    document.getElementById('a').value = str; 
    // Whatever else you need to do. 
} 

...或轮询textarea的价值...

(function() { 
    var text = getText(); 
    var getText = function() { 
     return document.getElementById('a').value; 
    } 

    setInterval(function() { 
     var newtext = getText(); 
     if (text !== newText) { 
      // The value has changed. 
     } 
     text = newText; 
    }, 100); 
})(); 

...或自己显式调用onchange()事件。

document.getElementById('a').onchange(); 

(假设你设定的事件了onchange财产。)

的解决方法是不是非常伟大的解决方案。无论哪种方式,当更新textareavalue属性时,您都需要进行一些干预以触发额外的代码。

+0

你肯定能做到这一点...见下文。 – 2011-04-26 07:22:21

+2

@Cos这是jQuery,其中OP从未提及过。你也明确地调用'change()',这基本上是我在我的答案中提出的。 – alex 2011-04-26 07:23:27

+0

@Alex jquery是javascript(或更确切地说是一个javascript集合),并且证明调用'.change()'将实现OP提出的目标是更好的指导,可以“做任何你需要做的事情” – 2011-04-26 10:34:04

-1

如果你可以使用jQuery,它会是这样的

$('#id_of_text_area').change(function(){ 
    //do something 
}); 
0

你可以强制回传从JavaScript,因此强制页面重新加载事件。在Page.GetPostBackEventReference()中,您可以处理事件并可能触发其他事件。

这不是一个很好的解决方案和吼声我真的建议你做的这一切直通JavaScript或下降的JavaScript,让.NET hadle一切,或许与Ajax.NET

以下link说明你做藿对于一个普通的按钮,但它不应该很难做出onchange事件。

0

使用jQuery你可以指定一个“变”处理程序,并调用处理程序是这样的:

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script> 
    <script type="text/javascript"> 
     $(document).ready(function() { 
      //makes 'DetectChange' the handler when TextBox1 changes... 
      $('#TextBox1').change(function() { 
       DetectChange(); 
      }); 
     }); 

     function DetectChange() { 
      alert("TextBox1 has been changed"); 
     } 

     function ClickTheButton() { 
      // .val actually 'changes the value' 
      // while you have to add .change() to invoke the actual change event handler... 
      $('#TextBox1').val("Changed When Button Clicked").change(); 

      //return false prevents the click event of the button from doing a post back 
      //keeping everything on the client for this sample.. 
      return false; 
     } 
    </script> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div> 
     <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 
     <input id="Button1" type="button" value="Change TextBox1" onclick="return ClickTheButton();" /> 
    </div> 
    </form> 
</body> 
</html> 
+1

为什么不直接将'DetectChange'传递给'click()'方法? – alex 2011-04-26 10:53:34

+1

@Alex OP陈述'但在我的情况下,我从Javascript中更改文本,所以我使用按钮的单击事件来模拟该场景的元素。我不知道'OP'使用的是什么,或者它是如何调用的,所以我只是简单地做了一些类似的演示。你是正确的,'.change'可以通过点击调用,如果这符合OP的需求,那么很好。 – 2011-04-26 11:24:52