Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect the change on input when it changed dynamically

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>
like image 924
Yosra Nagati Avatar asked Sep 07 '16 16:09

Yosra Nagati


3 Answers

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/

like image 190
Kodie Grantham Avatar answered Sep 29 '22 06:09

Kodie Grantham


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();"/>
like image 25
Sufian Saory Avatar answered Sep 29 '22 07:09

Sufian Saory


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>
like image 28
Ehsan Avatar answered Sep 29 '22 07:09

Ehsan