在外部分配值时,更改事件不适用于文本框 [英] change event not working for a textbox when the value is assigned externally

查看:69
本文介绍了在外部分配值时,更改事件不适用于文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本框和一个按钮。
当我点击按钮时,它会在文本框中设置一定的值。
我想在文本框的值发生变化时提交页面。

I have a textbox and a button. When I click the button, it sets certain value in the textbox. I want to submit the page whenever the value of the textbox is changed.

请检查这里

HTML:

<input type='text' class="set" size=50>
<input type="button" id="click" value="Click" />

JQuery:

$(document).ready(function () {
    $("input").change(function () {
        alert("Changed!");
    });
    $("#click").click(function () {
        $('.set').val('Why am I not getting the alert saying  - Changed! ');
    });
});

我在编辑文本框内容时能够触发更改事件。我知道更改当文本框失去焦点时会触发事件。当我通过按钮单击更改值时,情况不是这样。

I am able to trigger the change event when I am editing the textbox content.I know that the change event gets triggered when the textbox loses focus.This is not the case when I am changing the value by button click.

我看到了监视文本框以便更改的答案指定的时间间隔,比如0.1秒。

I have seen answers which monitors the textbox for change at a specified time interval , say 0.1 sec.

没有别的方法可以做到这一点。
谢谢。

Is there no other way for this to be done. Thanks.

编辑 - 1
* 很抱歉没有被在我的原始帖子中清除 *。

我的要求是每当输入框内容发生变化时触发事件 - 不一定只需点击一下按钮。我添加了一个按钮来解释问题。
更改可能是由于任何原因。

My requirement is to trigger an event whenever the inputbox content is changed - Not necessarily by the click of a button.I have added a button just to explain the problem. The change may be due to any reason.

所以,代码(在按钮点击功能内)

So,the code(inside the button click function)

$('.set').val('Hello').change();

无法解决问题。
希望我这次很清楚。

will not solve the problem. Hope I am clear this time.

请建议。

推荐答案

使用 change()函数设置值后手动触发事件。

Fire the event manually after setting the value using the change() function.

$(document).ready(function () {
    $("input").change(function () {
        alert("Changed!");
    });
    $("#click").click(function () {
        $('.set').val('Why am I not getting the alert saying  - Changed! ');
        $('.set').change();  //Manual fire of event.
    });
});

工作示例 http://jsfiddle.net/RUdu2/

这篇关于在外部分配值时,更改事件不适用于文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆