moses toh moses toh - 6 months ago 24
Javascript Question

How to send parameter in modal bootsrap?

Demo and full code is like this : https://jsfiddle.net/xzxrp7nn/9/

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 priceModal = '{"attributes":{"Code":"DBL","Total":"200000"},"DayPrice":{"Date":"2016-05-26","Rate":"200000"}}';

var isitable = '<button class="btn blue tes_button" data-toggle="modal" data-target="#priceModal" id="priceModal='+priceModal+'">Test get parameter json array</button>';
$("#tes").html(isitable);
}
});
});

$('#priceModal').on('show.bs.modal', function(e) {
//console.log('yes');
var param = e.relatedTarget.id;
// var hotel_code = $(this).data('id');
console.log(param);
// console.log(hotel_code);
})
});


When click button "Click me", It will display button "Test get parameter json array".

When click button "Test get parameter json array", I want send parameter
priceModal
to modal. Parameter
priceModal
contain json array. I do console.log(param); in
$('#priceModal').on('show.bs.modal', function(e) {
.

But the result :
priceModal={
.
It failed to get the value of priceModal

Any solution to solve my problem?

Thank you

Answer

When you call id="priceModal='+priceModal+'" you are incorrectly appending your json to your element's id.

A data attribute would be far more appropriate, something more like this:

success: function(data) {
  var priceModal = {"attributes":{"Code":"DBL","Total":"200000"},"DayPrice":{"Date":"2016-05-26","Rate":"200000"}};
  var isitable = '<button class="btn blue tes_button" data-toggle="modal" data-target="#priceModal" data-price-modal="">Test get parameter json array</button>';
  $("#tes").html(isitable).find('[data-price-modal]').data('price-modal',priceModal);
}


$('#priceModal').on('show.bs.modal', function(e) {
  var param = $('[data-price-modal]').data('price-modal');
  console.log(param);
})

working jsFiddle