1

Awesome evening guys,

I have added a table dynamically using the following jquery code.

$(#table tr:last).after('<tr><td class="tbValue"> </td></tr>');

After adding it, now I want to access it using the following code

$('.tbValue').click(function){
alert('this button is clicked');
});

To my surprise its not working. I think the button has an html property however I just cannot seem to get it.

2 Answers 2

2

Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call.

As you are creating elements dynamically.

You need to use Event Delegation. You have to use .on() using delegated-events approach.

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

General Syntax

$(parentStaticConainer).on(event, selector, eventHandler);

Example

$("#table").on('click', '.tbValue', function(){
    alert('this button is clicked')
});
Sign up to request clarification or add additional context in comments.

Comments

1

Just enclose the selector in " or '.

Like this... $('#table tr:last')

Check out this fiddle.

Here is the snippet.

$('#table tr:last').after('<tr><td class="tbValue"> B </td></tr>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='table'>
  <tr>
    <td class="tbValue">A</td>
  </tr>
</table>

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.