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.
JavaScript
x
<button class="btn btn-primary open" id="${t}" data-toggle="modal" style="color:white;" data-target="#infoModal">more info</button>
jQuery code:
JavaScript
< script type = "text/javascript" >
$(document).ready(function() {
$('.open').click(function() {
var obj = $(this).attr('id');
$("#show-data").html(obj);
});
}); <
/script>
Advertisement
Answer
- Split your data to get desire shape using
.split(' ')
. - Remove unnecessary character from data.
- Inside loop generate markup.
- Append markup on desire
div
.
JavaScript
$('.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);
});
JavaScript
.key {
color: red
}
.val {
color: green
}
JavaScript
<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>