How to detect the changes in input values when it is dynamically changed. as the change on txt2 clear the value in txt1 . I need to detect that it has cleared or changed.
Onchange does not do that.
<input id="txt1" type="text" onchange="SetDefault();" onpaste="this.onchange();" oninput="this.onchange();">
<br>
<input id="txt2" type="text" onchange="SetDefaultSecond();" onkeyup="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();">
<script>
function SetDefault(){
alert("Change1");
}
function SetDefaultSecond(){
$("#txt1").val('');
alert("Change2");
}
</script>
You can manually trigger the input event when you clear the first input like this:
<input id="txt1" type="text">
<br>
<input id="txt2" type="text">
<script>
$("#txt1").on("input", function() {
alert("Change1");
});
$("#txt2").on("input", function() {
$("#txt1").val('').trigger('input');
alert("Change2");
});
</script>
jsFiddle here: https://jsfiddle.net/dr0oabj1/
you need to use oninput event to capture any change to an input. it triggers every time the value changes due to typing/pasting etc. difference between onchange & oninput is onchange only triggers after focus goes off the input where as oninput triggers every time values changes due to any reason.
function SetDefault(){
alert("Change1");
}
function SetDefaultSecond(){
$("#txt1").val('');
alert("Change2");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input id="txt1" type="text" oninput="SetDefault();" />
<br>
<input id="txt2" type="text" oninput="SetDefaultSecond();"/>
Try this :
$(document).ready(function(){
$("#txt2").on("input",function(){
$("#txt1").val('');
console.log("Change2");
})
$("#txt1").on("input",function(){
console.log("Change1");
})
})
Final code :
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
Text 1 : <input id="txt1" type="text">
<br><br>
Text 2 : <input id="txt2" type="text">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#txt2").on("input",function(){
$("#txt1").val('');
console.log("Change2");
})
$("#txt1").on("input",function(){
console.log("Change1");
})
})
</script>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With