Skip to content
Advertisement

How to print Java object in modal using jQuery

I am trying to print object data in modal using jQuery. When I click the button it sends the Java object to jQuery and then prints it but it is printing in this format:

Trip [tid=1, tname=North, tplace=Ladhak, tpackage=12000, tfrom=2022-05-21, tto=2022-05-31, lastdate=2021-12-22, tinfo=XYZ]

I want to access data of the object and display it.

<button class="btn btn-primary open" id="${t}" data-toggle="modal" style="color:white;" data-target="#infoModal">more info</button> 

jQuery code:

    < script type = "text/javascript" >
      $(document).ready(function() {
        $('.open').click(function() {
          var obj = $(this).attr('id');
          $("#show-data").html(obj);
        });
      }); <
    /script>

Advertisement

Answer

  1. Split your data to get desire shape using .split(' ') .
  2. Remove unnecessary character from data.
  3. Inside loop generate markup.
  4. Append markup on desire div.

$('.open').click(function() {
  var html = "";
  var obj = "Trip [tid=1, tname=North, tplace=Ladhak, tpackage=12000, tfrom=2022-05-21, tto=2022-05-31, lastdate=2021-12-22, tinfo=XYZ]";

  var data = obj.substr(obj.indexOf(' ') + 1).replace('[', '').replace(']', '').split(' ');
  $.each(data, function(index, value) {
    var key = value.split('=')[0]; // format these data on your desire shape
    var val = value.split('=')[1];
    html += '<span class="key">' + key + ' </span>';
    html += '<span class="val">' + val + ' </span>';
    html += '</br>';
  });
  $("#show-data").html(html);
});
.key {
  color: red
}

.val {
  color: green
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn btn-primary open" id="${t}" data-toggle="modal" style="color:white;" data-target="#infoModal">more info</button>

<div id="show-data"></div>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement