button does not seem to be in DOM

1

Good night, 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 }); of the table comes a simple alert (all within $ (document) .ready):

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

But when clicking nothing happens, if you inspect the button it will appear the id show . The same thing happens if I put onclick="metodo();" right on the element and create this method down, in console it informs that 'method' was not found. Any idea? It sounds simple but I'm stuck with it. vlw

    
asked by anonymous 24.07.2016 / 00:56

1 answer

1

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

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

Example assigning event to element of its form before creating it:

See that it will not 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>

Exampleassigningeventtoelementoftheotherformevenbeforecreatingit:

Seewhatwillworknow.

$(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 for you.

    
24.07.2016 / 02:23