Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically detect if textbox value is change

Is it possible to detect the change of a textbox even if that textbox value is not entered by user like the below scenario? I have some scenarios like when the page is loading for the first time the texbox get loaded with data.

$("#txt1").change(function(){
  $("#txt2").val("1")
  //$("#txt2").change();
});

$('#txt2').on("change", function() {
  // some computation will happen here.
  alert("1");
});

$("#btn1").click(function(){
  $("#txt2").val("1");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" id="txt1">
<input type="text" id="txt2" name='text1'>
<button id="btn1">
    Click
</button>
like image 740
Traf De Law Avatar asked Mar 27 '26 19:03

Traf De Law


1 Answers

The value changed by JavaScript does not trigger any event so you just can't catch event in this case. You can implement a watcher to your input value using interval

var oldValue = $("#txt2").val();
setInterval(function() {
    var currentValue = $("#txt2").val();
    if (currentValue !== oldValue) {
      $("#txt2").trigger("change");
      oldValue = currentValue;
    }
}, 100);

$("#txt1").change(function(){
  $("#txt2").val("1")
});

$('#txt2').on("change", function() {
  // some computation will happen here.
  alert("1");
});

$("#btn1").click(function(){
  $("#txt2").val("1");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<input type="text" id="txt1">
<input type="text" id="txt2" name='text1'>
<button id="btn1">
Click
</button>
like image 118
ChickenSoups Avatar answered Mar 29 '26 07:03

ChickenSoups



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!