0

I have added an input via the append function. But the keyup function is not working on the appended input.

When after clicking on add button the new input is visible but the keyup function is not working.

Can someone help so that keyup function works on each input?

    $(document).ready(function() {
        //Try to get tbody first with jquery children. works faster!
        var tbody = $('#myTable').children('tbody');

        //Then if no tbody just select your table 
        var table = tbody.length ? tbody : $('#myTable');


        $('button').click(function() {
            //Add row
            table.append(
                '<tr><td>2</td><td><input class="keyp" id="inputform" type="text"></td><td class="sid"></td></tr>'
            );
        });

        $('.keyp').on("keyup input", function() {
            $('.keyp').parent().siblings(".sid").html($(this).val());
        });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <button>Add row</button>
    <table id="myTable" class="table">
        <tbody>
            <tr>
                <td>1</td>
                <td><input class="keyp" id="inputform" type="text"></td>
                <td class="sid"></td>
            </tr>
        </tbody>
    </table>

1
  • 1
    Add the event listener to the table instead and use event delegation: $('table').on("keyup input", '.keyp', function()... Commented May 16, 2021 at 8:44

1 Answer 1

1

Thanks to @andy I got the answer.

Have to use event delegation so the updated js code for keyup function is

$('table').on("keyup input", '.keyp', function() {
  $(this).parent().siblings(".sid").html($(this).val());
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.