4

JSFIDDLE

Html Code:

<body>
    <input value="123">
    <button>button</button>
</body>

Js Code(using JQuery 1.2.0):

$(function(){
    $("button").click(function(){
        $("input").val("balabala...");
    });

    $("body").on("change","input",function(){
        alert("change");
        alert($("input").val());
    });
});

Question:
At the beginning, the value of the input is "123".

When I change the text through editing by hands and click other places not the input field, the change event of the input will trigger.

However, when I click the button, which will also change the value of the input, the change event of the input will not work.

Thanks for any help.

Pedro Estrada
  • 2,324
  • 2
  • 14
  • 24
Shaowei Ling
  • 186
  • 10

2 Answers2

7

The change event is not triggered when changing the value programatically with code, you have to trigger it yourself

$(function(){
    $("button").click(function(){
        $("input").val("balabala...").trigger('change');
    });

    $("body").on("change","input",function(){
        alert("change");
        alert($("input").val());
    });
});

FIDDLE

adeneo
  • 303,455
  • 27
  • 380
  • 377
1

JSFiddle

You need to append .change() onto the click function:

$(function(){
    $("button").click(function(){
        $("input").val("balabala...").change();

    });

    $("body").on("change","input",function(){
        alert("change");
        alert($("input").val());
    });
});
Albzi
  • 15,201
  • 5
  • 43
  • 61