4

I can not figure out why the following code does not work. JSFIDDLE LINK

$(document).ready(function () {
    addInput();
});

var limit = 30;
function addInput() {
    var numberOfRows = $("#shipping tr").size();
    var id = numberOfRows;
    if (numberOfRows == limit) {
        alert("You have reached the limit of adding " + limit + " inputs");
    } else {
        $('#shipping').append('<tr id="rate' + id + '"></tr>');
        $('tr#rate' + id).append('<td></td>');
        $('tr#rate' + id).append('<td><input type="text" name="rate" /></td>');
    }
    $('input[name=rate]').on('keyup', 'input', function () {
        alert('YAY');
        return false;
    });
}

I am trying to assign a keyup function to the inputs that I add dynamically.

Expected output: YAY! inside a popup box

Please help!

1
  • see the demo in answer.. Commented Apr 19, 2013 at 3:40

2 Answers 2

7

Attach an keyup event handler to shipping table, and the event will bubble up from the input[name="rate"] to shipping table:

$('#shipping').on('keyup', 'input[name="rate"]', function () {
    alert('YAY');
    return false;
});

DEMO

Sign up to request clarification or add additional context in comments.

Comments

3

You need to add delegation to document because its added to the document.

Example

$(document).on('keyup', 'input[name="rate"]', function () {
    alert('YAY ');
});

Working Demo

1 Comment

It doesn't make sense to go up all the way to document when the input[name="rate"] elements are added to the [id="shipping"] element

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.