0

If I change the input text of task1, the text box task2 is changed as expected.

But if I change the text box task2, text box task3 is not changed.

What is wrong with my code?

<!DOCTYPE html>
<html lang="en">
    <head>
        <script type="text/javascript"  src="D:\Website\Jquery/jquery-2.1.4.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $("#tasks1").change(function () {
                    alert('testingphase1');
                    $("#tasks2").replaceWith('<input type="text" id="tasks2" placeholder="t2">');
                });
                $("#tasks2").change(function () {
                    alert('testingphase2');     
                    $("#tasks3").replaceWith('<input type="text" id="tasks3" placeholder="t3">');
                });
            });
        </script>
    </head>

    <body>
        <input type="text" id="tasks1" >
        <input type="text" id="tasks2" placeholder="taks2">
        <input type="text" id="tasks3" placeholder="taks3">
    </body>
</html>
Falko
  • 15,326
  • 12
  • 50
  • 91

1 Answers1

1

The problem is you are replacing the dom elements which means the handlers bound to the previous elements are lost.

Use event delegation to handler events of dynamic elements

$(document).ready(function () {
    $(document).on('change', '#tasks1', function () {
        alert('testingphase1');
        $("#tasks2").replaceWith('<input type="text" id="tasks2" placeholder="t2">');
    });
    $(document).on('change', '#tasks2', function () {
        alert('testingphase2');
        $("#tasks3").replaceWith('<input type="text" id="tasks3" placeholder="t3">');
    });
});

Note: If you can explain your requirement, there could be better solution than just replacing the element

Arun P Johny
  • 365,836
  • 60
  • 503
  • 504
  • I tried this, but didn't works out.. Still behaving the same way.. IF needed I will provide you the exact requirement. – KARTHICK JOTHIMANI Aug 04 '15 at 15:32
  • There are three drop downs in the page for the first row. If one drop down is changed then the value for the other two drop down should be changed as well. There's Add button, if add btn is clicked then similar three drop downs will be added in the next row. The functionality is same for all the rows. Can you please suggest a method. – KARTHICK JOTHIMANI Aug 06 '15 at 05:15