button doesn’t seem to be in the DOM

Asked

Viewed 42 times

1

Good evening, I have a jquery table where in a column I return a button

{ "data" : 'sla.value', 'render': function ( data, type, full, meta ) {
  return ' <button id="show" type="button">Click</button>'; }

After closing the}); table comes a simple alert (all within $(Document). ready):

 $('#show').click(function(){
  alert('oi');
   });

But when you click nothing happens, if you inspect the button it shows the id show. The same thing happens if I put it like this onclick="metodo();" direct into the element and create this method below, in the console informs that 'method' was not found. Any idea? It seems simple but I’m stuck in it. vlw

1 answer

1


Your button is being created dynamically. Usually when we want to find this type of element in the DOM, we use this:

$(document).on('click', '#show', function(){
    alert('oi');
})

Example assigning the event to its shape element before creating it:

See that it won’t work.

$('#show').click(function(){
	alert('oi');
});
$('body').append('<button id="show" type="button">Click</button>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Example assigning the event to the element in the other way even before creating it:

See that now it will work.

$(document).on('click', '#show', function(){
   alert('oi');
})
$('body').append('<button id="show" type="button">Click</button>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

See if it works in your case.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.