Reputation: 153
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>
Upvotes: 3
Views: 279
Reputation: 975
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>
Upvotes: 2
Reputation: 1720
As you know that on textbox1 change event you are changing second textbox value, you need to trigger it manually
$(document).ready(function () {
$("#txt1").change(function () {
$("#txt2").val("1")
$("#txt2").trigger("change");
});
$("#txt2").change(function () {
alert("1");
});
})
Upvotes: 1