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,384
  • 2
  • 16
  • 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
  • 312,895
  • 29
  • 395
  • 388
  • Ooh, just out of interest, what's the difference between using `.trigger('change')` and `.change()`? – Albzi May 08 '14 at 15:26
  • No difference for this case really, jQuery just has a special `trigger()` method that does this, and it accepts more options than just using `.change()` – adeneo May 08 '14 at 15:30
  • @BeatAlex Both of methods work, but I do not know the difference in details. – Shaowei Ling May 08 '14 at 15:32
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,431
  • 6
  • 46
  • 63