change event not working for a textbox when the value is assigned externally(外部分配值时,更改事件不适用于文本框)
问题描述
我有一个文本框和一个按钮.当我单击按钮时,它会在文本框中设置某些值.每当文本框的值发生更改时,我都想提交页面.
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/
这篇关于外部分配值时,更改事件不适用于文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:外部分配值时,更改事件不适用于文本框
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01