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

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

问题描述

我有一个文本框和一个按钮.当我单击按钮时,它会在文本框中设置某些值.每当文本框的值发生更改时,我都想提交页面.

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天全站免登陆