0

What is the right 'selector' to use to make 'My Button' work? I've searched this site, none seems to work for me?

<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="robots" content="index, all" />
<title>Example</title>
</head>

<body>
    <div id="result"><!--results-->
    </div>
<!-- jQuery -->
<script src="js/jquery.min.js"></script>
<script type="text/javascript">
    $( document ).ready(function() {
        //generate table
        htmlx='<table class="table table-condensed">';
        htmlx+='<tr><td align="center"><button type="button" id="bt_kgt2" name="bt_kgt" class="btn btn-info">My Button</button></td></tr>';
        htmlx+='</table>';
        $('#result').html(htmlx);               
    });

    $("#bt_kgt2").on( "click", function() {
        alert ("button clicked!");
    });
</script>
</body> 
</html>
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
Lanz Man
  • 15
  • 2

1 Answers1

1

You are trying to bind the click event handler before the element is adding. You have two option to bind click event handler either bind after adding element to dom.

$(document).ready(function() {
  //generate table
  htmlx = '<table class="table table-condensed">';
  htmlx += '<tr><td align="center"><button type="button" id="bt_kgt2" name="bt_kgt" class="btn btn-info">My Button</button></td></tr>';
  htmlx += '</table>';
  $('#result').html(htmlx);
  $("#bt_kgt2").on("click", function() {
    alert("button clicked!");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result">
  <!--results-->
</div>

Or use event delegation to listen dynamically added element

$(document).ready(function() {
  //generate table
  htmlx = '<table class="table table-condensed">';
  htmlx += '<tr><td align="center"><button type="button" id="bt_kgt2" name="bt_kgt" class="btn btn-info">My Button</button></td></tr>';
  htmlx += '</table>';
  $('#result').html(htmlx);

});

$('#result').on("click", "#bt_kgt2", function() {
  alert("button clicked!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result">
  <!--results-->
</div>
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188