moses toh moses toh - 6 months ago 14
HTML Question

How to send id parameter based on which button is clicked?

Demo and full code is like this : https://jsfiddle.net/oscar11/o5qn5gum/8/

My HTML code is like this :

<button type="button">Click Me</button>

<div id="tes">

</div>


<!-- Modal Currency-->
<div class="modal fade" id="priceModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">


</div>
<div class="modal-body">

</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>


My Javascript code is like this :

$(document).ready(function(){
$("button").click(function(){

$.ajax({
//type: 'POST',
//url: 'script.php',
success: function(data) {
var isitable = '';
isitable += '<br><button class="btn btn-primary tes" id="NationCd=ID&CityCd=JKT">Book 1</button><br><br>';
isitable += '<button class="btn btn-primary test" id="NationCd=ID&CityCd=BAI">Book 2</button><br><br>';
isitable += '<button class="btn btn-primary test" id="NationCd=ID&CityCd=JOG">Book 3</button><br>';

// console.log(isitable);
$("#tes").html(isitable);
}
});
});

$(".test").click(function(){
console.log('tes');
var id = this.id;
console.log(id);
});
});


When click button "Click me", It will display three button. Look jsfidde.

When click the button (for example, I click button "book 1"), It will send parameter id. I do
console.log(this.id);
in
$(".test").click(function(){
, but it's not working.

Any solution to solve my problem?

Thank you

Answer

Since you do an AJAX call, you have to put your click event in the success part like this :

$(document).ready(function(){
  $("button").click(function(){

    $.ajax({
      //type: 'POST',
      //url: 'script.php',
      success: function(data) {
        var isitable = '';
        isitable += '<br><button class="btn btn-primary test" id="NationCd=ID&CityCd=JKT">Book 1</button><br><br>';
        isitable += '<button class="btn btn-primary test" id="NationCd=ID&CityCd=BAI">Book 2</button><br><br>';
        isitable += '<button class="btn btn-primary test" id="NationCd=ID&CityCd=JOG">Book 3</button><br>';

        // console.log(isitable);
        $("#tes").html(isitable);
        $(".test").click(function(){
          console.log('tes');
          var id = this.id;
          console.log(id);
        });

      }
    });
  });


});

Fiddle

Comments