简体   繁体   English

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

[英]Fire onchange event for TextBox when readonly is true

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.我在单击按钮时调用 ChangeText 方法。 But it is not firing the textchange event for the textbox.但它不会触发文本框的 textchange 事件。

Can anybody tell me what is wrong here?有人能告诉我这里有什么问题吗?

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');
   });
 });

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();

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();
}

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.但是您可以通过触发该元素上的特定事件来实现这一点。 Eg $('input[id$=_txtTest]').trigger('change');例如$('input[id$=_txtTest]').trigger('change');

I hope this helps someone.我希望这可以帮助别人。

onkeypress event or one of the several other events : onkeypress事件其他几个事件之一

Since the read-only field doesn't really change;由于只读字段并没有真正改变; the onChange event doesn't trigger on it. onChange事件不会触发它。 However;然而; there are several other events that you can listen to.您还可以收听其他几个事件

Here's a short demo:这是一个简短的演示:

 input { font-size: 16px; line-height: 30px; padding: 3px; border: 2px darkblue solid; }
 <script> function sayHi(evt) { alert('Are you tyring to edit a read-only? Click OK for details.') alert(JSON.stringify({ keyCode: evt.keyCode, charCode: evt.charCode, altKey:evt.altKey, ctrlKey: evt.ctrlKey, shiftKey: evt.shiftKey }), null, 2); } </script> <input onkeypress="sayHi(event);" readonly placeholder="A readonly field..." />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM