TextBox onchange when setting value with javascript (jQuery)

风流意气都作罢 提交于 2019-12-08 04:07:13

问题


    $(document).ready(function() {
        $('#text').live('change', function() {
            alert('hello');
        });
        $('#button').live('click', function() {
            $('#text').val('some text');
        });
    });  

    <div>
        <input type="button" id="button" value="Click Me" />
        <input type="text" id="text" />
    </div>

How can I make the change function on the textbox trigger when I click the button? Thanks


回答1:


You can use .change() (the shortcut) or .trigger(), like this:

$('#button').live('click', function() {
  $('#text').val('some text').change();
});

Or this:

$('#button').live('click', function() {
  $('#text').val('some text').trigger('change');
});

Either method works to trigger any change event handlers you've added, you can test it here.



来源:https://stackoverflow.com/questions/3202716/textbox-onchange-when-setting-value-with-javascript-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!