Javascript 当 readonly 为 true 时触发 TextBox 的 onchange 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14332972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:24:49  来源:igfitidea点击:

Fire onchange event for TextBox when readonly is true

javascriptjqueryhtml

提问by Ashwani K

I am trying to have some functionality on change of a textbox which is readonly. But when I am trying to update the textbox using javascript, the change event is not firing for the textbox.

我正在尝试更改只读文本框的一些功能。但是当我尝试使用 javascript 更新文本框时,不会为文本框触发更改事件。

<script type="text/javascript">
        $(document).ready(function () {
            $('input[id$=_txtTest]').bind("change", function () {
                alert("test");
            });
                        });
        function ChangeText() {
            $('input[id$=_txtTest]').val('hello');
         }
    </script>

I am calling ChangeText method on click of a button. But it is not firing the textchange event for the textbox.

我在单击按钮时调用 ChangeText 方法。但它不会触发文本框的 textchange 事件。

Can anybody tell me what is wrong here?

有人能告诉我这里有什么问题吗?

回答by Jai

Well you have to do this way: http://jsfiddle.net/kmvSV/1/

那么你必须这样做:http: //jsfiddle.net/kmvSV/1/

 $(document).ready(function () {
   $('input[id$=_txtTest]').bind("change", function () {
     alert($(this).val());
   });
   $('button').bind("click", function () {
     $('input[id$=_txtTest]').val('hello').trigger('change');
   });
 });

回答by Christiaan Westerbeek

The change event is triggered by real user events only not javascript actions.

更改事件仅由真实用户事件触发,而不是由 javascript 操作触发。

You may trigger the change event, like so:

您可以触发更改事件,如下所示:

$('input[id$=_txtTest]').val('hello').change();

回答by Pranay Rana

you can do like this

你可以这样做

function setValueOfTextBox()
{
    var myElement = document.getElementById("textboxid");
    myElement.value = "hello";
    //following code fire change event for you text box
    if (myElement.onchange) 
         myElement.onchange();
}

回答by jking

I believe that for some security reason, the events are not fired. But you can achieve this by triggering the specific event on that element. E.g. $('input[id$=_txtTest]').trigger('change');

我相信出于某种安全原因,事件不会被触发。但是您可以通过触发该元素上的特定事件来实现这一点。例如$('input[id$=_txtTest]').trigger('change');

I hope this helps someone.

我希望这可以帮助别人。