2

I am working on the below snippet. Why am I not able to detect the input change using this?

$("#fname").on("change", function () {
   console.log("The text has been changed.");
});

$("button").on("click", function () {
    $("#fname").text('Alex');
    $("#fname").val('Alex');
});

$("#fname").on("change", function () {
   console.log("The text has been changed.");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <input type="text" id="fname" name="fname"><br><br>
<button type="button">Click Me!</button>
halfer
  • 19,824
  • 17
  • 99
  • 186
Behseini
  • 6,066
  • 23
  • 78
  • 125

2 Answers2

2

This only gets triggered if the user sets the value. You can trigger it manually.

$("#fname").val('Alex').change();
Kruspe
  • 626
  • 6
  • 19
1

You have to trigger change programmatically if you are applying the change programmatically.

$("button").on("click", function () {
    $("#fname").text('Alex').trigger('change');
    $("#fname").val('Alex').trigger('change');
});

$("#fname").on("change", function () {
   console.log("The text has been changed.");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <input type="text" id="fname" name="fname"><br><br>
<button type="button">Click Me!</button>
Udo E.
  • 2,665
  • 2
  • 21
  • 33