Populating string with dynamic data - javascript

I have the following line of code inside me JS:
'<a class="txt333 clps" data-toggle="collapse" aria-expanded="false" '+
'href="#collapse_reqConf'+sent+'" '+
'aria-controls="collapse'+sent+'" '+
'data-parent="#accordion_reqConf'+sent+'">'
Which populates var sent and produces the following results (from source view):
<a class="txt333 clps" data-parent="#accordion_reqConf137" aria-controls="collapse137" href="#collapse_reqConf'+sent+'" aria-expanded="false" data-toggle="collapse">
I cannot figure out why the one within href attribute is not being inserted properly...
UPDATE: WORKING ANSWER IN MY LAST COMMENT.

Since you're using jQuery anyways, you try something like the following to create DOM elements using jQuery. Personally, I feel that creating elements using strings of HTML is error-prone, makes the code hard to read and debug. I create the <a></a> element that you are having an issue with using jQuery and append its containing elements using elements created from string.
var inner = '<div class="row">'+
'<div class="col-xs-9 col-sm-8">'+
'<table class="w100p text-success b">'+
'<tr>'+
'<td width="50%" class="nowrap pad10rt">'+ '<i class="fa fa-clock-o fa-lg valignMid xtraSm"></i> 4:00 pm'+'</td>'+
'<td width="50%"><i class="fa fa-user fa-lg valignMid xtraSm"></i> x '+part+'</td>'+
'</tr>'+
'</table>'+
'</div>'+
'<div class="col-xs-3 col-sm-4 text-right">'+
'<i class="indicator fa fa-fw fa-chevron-right"></i>'+
'</div>'+
'</div>';
var attribs = {
"class": "txt333 clps",
"data-toggle": "collapse",
"aria-expanded": false,
"href": "#collapse_reqConf" + sent,
"aria-controls": "collapse" + sent,
"data-parent": "#accordion_reqConf" + sent
};
var elStr = $('<a>').attr(attribs).append($(inner)).prop('outerHTML');
console.log(elStr);

Related

How to pass a json string as parameter in javascript?

I have received a json string like this:
The Api response as following list:
[
{
"id": "1018491557",
"results": "{\"combo\":\"3,4,13,14\"}",
"time": "2020-07-13T16:11:03.082Z",
"modifiedTime": "0001-01-01T00:00:00",
"status": "SUCCESS"
},...
]
Then I mockup html like this and I need to open the modal to show single details:
var res =
'<a href="#" onclick="openDetails(\''+value.id+'\', \''+value.results+'\', \''+value.time+'\', \''+value.modifiedTime+'\')">';
$(".list").append(res);
But I just cant get the right format of RESULTS to display.
function openDetails($id, $res, $time, $modTime){
$("#DetailsModal").remove();
var modal =
'<div id="DetailsModal" class="modal fade" tabindex="-1" role="dialog">'+
'<div class="modal-dialog" role="document">'+
'<div class="modal-content">'+
'<div class="modal-header">'+
'<h5 class="modal-title">Details</h5>'+
'<button type="button" class="close" data-dismiss="modal" aria-label="Close">'+
'<span aria-hidden="true">×</span>'+
'</button>'+
'</div>'+
'<div class="modal-body">'+
'<p>ID: '+$id+'</p>'+
'<p>Sesults: '+$res+'</p>'+
'<p>Time: '+$time+'</p>'+
'</div>'+
'<div class="modal-footer">'+
'<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>'+
'</div>'+
'</div>'+
'</div>'+
'</div>';
$("body").append(modal);
$("#DetailsModal").modal({
backdrop:"static",
keyboard:false,
show:true
});
}
Anyone can point me out here? Thanks
solved!
Okay~ it turns out no need to quote the string again. problem solved by replacing the double quotes to single.
<a href="#" onclick="openDetails(\''+value.id+'\', '+value.results.replace(/"/g, "'")+', \''+value.time+'\', \''+value.modifiedTime+'\')">
I don't know exactly what your code is, but if you get a json string you have to use JSON.parse() to transform it into a JavaScript object.
var result = JSON.parse('{"combo":"3,4,13,14"}');
...
<a href="#" onclick="openDetails(result)">

Bootstrap 4 popover added dynamically cannot dismiss

I have Bootstrap 4 popovers added dynamically to a table.
I initialize my popover like this:
// Initialize popover
$('body').popover({
html: true,
template:
'<div class="popover popover-row-field" role="tooltip">' +
'<div class="arrow"></div>' +
'<button type="button" class="btn-popover-header btn-edit-popover-close float-right text-primary" aria-label="Close">' +
'<i class="fal fa-check"></i>' +
'</button>' +
'<button type="button" data-action="undo" class="btn-popover-header action-button text-primary float-right">' +
'<i class="fal fa-undo"></i>' +
'</button>' +
'<h3 class="popover-header"></h3>' +
'<div class="popover-body"></div>' +
'</div>',
placement: 'bottom',
trigger:'click',
position: 'relative',
selector: '.btn-edit-cell',
});
I have an event listener for a close button on the popover:
// Close popover by clicking the X
$(document).on('click', '.btn-edit-popover-close', function() {
$('.btn-edit-cell').popover('hide').popover();
});
I then clone a template row and add it to the table:
<td class="field-editor-input align-top">
<button type="button" class="btn-popover-header text-light btn-edit-cell save-btn-group" data-link="{{ $col->header }}-new"
data-html="true" title="{{ pretty_heading($col->header) }}" data-row-id="#row-template-new"
data-content="<textarea id='text-{{ $col->header }}-new' name='{{ $col->header }}' class='form-control popover-edit-field'></textarea>">
<i class="fal fa-pen text-light"> </i>
</button>
<div id="div-{{ $col->header }}-new" data-orig=""></div>
</td>
The popover opens OK but the close button does not fire.
Additionally, the popover does not stay fixed to its target if I scroll the page.
Thanks

append() fail to make boostrap component works

This drive me crazy, i've this simple html bootstrap-gentelella template that works almost in every page of the site that im developing, the html is so simple:
(this code make the part in the class "x_content" visible or not visible by clicking the "collapse-link" class in the "a" tag)
<div class="x_panel">
<ul class="nav navbar-right panel_toolbox">
<li>
<a class="collapse-link freccia_feed">Replies
<i class="fa fa-chevron-up"></i>
</a>
</li>
</ul>
<div class="x_content" style="display: none;">
<div class="input-group col-md-12 col-sm-12 col-xs-12">
<input data-role="tagsinput" id="risposta_'+j+'_D_'+element+'" class="form-control risposta_domanda_'+element+'" name="reply" value="" placeholder="Insert one solution" type="text">
<span class="input-group-btn">
<button id="elimina_risp_'+j+'_D_'+element+'" class="btn btn-danger glyphicon glyphicon-trash" > </button>
</span>
</div>
</div>
</div>
be carefull that the part like id="risposta_'+j+'_D_'+element+'" have no sense in this static part, and rendered as is it, just for example, I use that in the jQuery function that fail to make it works!
here:
$("#domanda_"+element).append(
'<div class="x_panel">'+
'<ul class="nav navbar-right panel_toolbox">'+
'<li>'+
'<a class="collapse-link freccia_feed" >Replies'+
'<i class="fa fa-chevron-up"></i>'+
'</a></li></ul>'+
'<div class="x_content" style="display: none;">'+
'<div class="input-group col-md-12 col-sm-12 col-xs-12">'+
'<input data-role="tagsinput" id="risposta_'+j+'_D_'+element+'" class="form-control risposta_domanda_'+element+'" name="reply"'+
'value="" placeholder="Insert one solution" type="text">'+
'<span class="input-group-btn"><button id="elimina_risp_'+j+'_D_'+element+'" class="btn btn-danger glyphicon glyphicon-trash" >'+
'</button></span>'+
'</div></div></div>');
I've tried many options to make this string works inside append() and the only one that seems working it to wrap the whole string with single ' using double " for ids class etc. and then inject javascript variable with single ' and +. Same thing for new line.
I even try to escape the whole string with online escape tools like https://www.freeformatter.com/javascript-escape.html
but still the same result, the component not works if is appended!
the problem is in the "inizialization" of the class ".collapse-link" by gentelella js.
So i move the function under my "div" generation function's.
I even add a "unbind()" func to resolve the problem that "inizialization" can toggle even the allready rendered div making them open anc closing several time...
thats the code if someone can find it usefull
cheers
$(".collapse-link").unbind("click");
$(".collapse-link").on("click", function() {
var a = $(this).closest(".x_panel")
, b = $(this).find("i")
, c = a.find(".x_content");
a.attr("style") ? c.slideToggle(200, function() {
a.removeAttr("style")
}) : (c.slideToggle(200),
a.css("height", "auto")),
b.toggleClass("fa-chevron-up fa-chevron-down")
});

Results in order with first ajax but inside for loop order randomly changed. Why?

This is weird really for me . I am not able to understand why this is happening, I want someone to explain this please.
Okay, I am running One ajax call in which i am calling [data] and running it through a for loop where i am getting all the database values then i am running another ajax call to check the other condition where i am getting other value. Everything is working great as i want. The problem is the order in which i am getting the values after the success of the second ajax is random. Which is totally not understandable.
In my first ajax call i am getting results in right order i.e DESC order.
Please explain me why.
function get_filter_data(val) {
$.ajax({
type: "POST",
url: "filter_data.php",
dataType: 'json',
data:'rating='+val,
success: function(data){
var str = '';
var cide = $('#cSessionid').val();
//console.log(cide+'-session-id');
for(var i in data)
{
var ide = data[i].id;
var username = data[i].username;
var u_name = username.toLowerCase().replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
var email = data[i].email;
var ref_number = data[i].ref_number;
var rating = data[i].rating;
var title = data[i].review_title;
var desc = data[i].review_desc;
var pubdate = data[i].pubdate;
//console.log(data[i].id+'-first-id');
$.ajax({
type: "POST",
url: "add_edit_delete.php",
dataType: 'json',
cache: false,
data: {
username: username,
u_name: u_name,
email: email,
ref_number : ref_number,
rating : rating,
title : title,
desc : desc,
pubdate : pubdate,
ppid : ide
},
success: function(data){
var eip = data.ipadt;
if(eip === cide){
var ddc = '<div class="editndeletebox"><span>Edit</span><a class="deletereviewn" href="#"><span>Delete</span></a></div>';
}else{
var ddc = '<span></span>';
}
str += '<div class="review pageable-item-js item clearfix" data-reviewmid="57c5e5e20000ff000981e1be">';
str += '<div class="user-info clearfix">';
str += '<div class="user-review-name clearfix"><a class="user-review-name-link" rel="nofollow" title="go to ' + data.u_name + ' profile" href="../users/users.php?review='+data.pid+'">';
str += data.u_name;
str += '</a></div>';
str += '<div class="clearfix">1 review </div>';
str += '</div>';
str += '<div class="review-info clearfix">';
str += '<input type="hidden" id="dneid" value="'+data.pid+'" />';
str += ddc;
str += '<div class="star-rating count-'+data.rating+' size-medium clearfix">';
str += '<div class="star-1"><img src="../community/shared/sprite_star.png" class="star-image" alt=""></div>';
str += '<div class="star-2"><img src="../community/shared/sprite_star.png" class="star-image" alt=""></div>';
str += '<div class="star-3"><img src="../community/shared/sprite_star.png" class="star-image" alt=""></div>';
str += '<div class="star-4"><img src="../community/shared/sprite_star.png" class="star-image" alt=""></div>';
str += '<div class="star-5"><img src="../community/shared/sprite_star.png" class="star-image" alt=""></div>';
str += '</div>';
var publish_date = $.timeago(data.pubdate);
var publish_date = $.trim(publish_date);
// Published Wednesday, October 24, 2012
if(publish_date != "false") {
show_date = publish_date;
}
else {
var dayNames = [
"Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saterday"
];
var monthNames = [
"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"
];
var date = new Date(data.pubdate);
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
var dayIndex = date.getDay();
var show_date = 'Published ' + dayNames[dayIndex] + ', ' + monthNames[monthIndex] + ' ' + day + ', ' + year;
}
str += '<time datetime="'+data.pubdate+'" class="ndate timeago" title="'+data.pubdate+'" >';
str += show_date + '<span title=""></span>';
str += '</time>';
if (data.ref_number == 11) {
str += '<div class="hover_tip"><div class="review-verified"><div class="review-verified-tooltip-text-hidden">'+ data.u_name +' was invited to write this review by The Logo Company. Learn more.</div><span class="icon icon-ok-sign"></span> Verified order<div class="review-verified-tooltip-container" style="width: 421px;"><p class="review-verified-tooltip-text">'+data.u_name+' was invited to write this review by The Logo Company. Learn more.</p></div></div></div>';
}
else {
str += '<div class="hover_tip"><div class="review-verified"><div class="review-verified-tooltip-text-hidden">Thelogocompany.net were not able to verify which order correlates to this review. Learn more.</div><span class="icon icon-ok-sign"></span> Unverified order<div class="review-verified-tooltip-container" style="width: 421px;"><p class="review-verified-tooltip-text">Thelogocompany.net were not able to verify which order correlates to this review. Learn more.</p></div></div></div>';
}
//<span class="icon icon-ok-sign"></span>
str += '<h3 class="review-title en h4">';
str += '<a class="review-title-link" rel="nofollow" href="../reviews/reviews.php?review='+data.pid+'">';
str += data.title;
str += '</a></h3><div class="review-body">';
str += data.desc;
str += '</div>';
str += '<div class="review-actions clearfix"><div class="btn-action clearfix "><div class="icon icon-thumbs-up circle-action blue-action" id="pressme_'+data.pid+'" onclick="funn('+data.pid+')"; title="Find useful" ><i class="fa fa-thumbs-up" aria-hidden="true"></i></div><div class="number-box" id="box_'+data.pid+'" style="display:none"><div class="text useful-counter-js" id="val_'+data.pid+'"></div></div></div><div class="btn-action clearfix" ><div class="icon icon-report circle-action notify" id='+data.pid+' title="Notify Compliance" onclick="fun('+data.pid+');"><i class="fa fa-flag" aria-hidden="true"></i></div></div><div class="btn-action clearfix" data-social-share-url="https://www.trustpilot.com/reviews/57c5e5e20000ff000981e1be" data-event-source="CompanyProfile" data-shared-object="SellerReview"><div class="icon icon-facebook circle circle-action social-share-facebook-js" title="Share on Facebook"><i class="fa fa-facebook" aria-hidden="true"></i></div></div><div class="btn-action clearfix" data-social-share-url="https://www.trustpilot.com/reviews/57c5e5e20000ff000981e1be" data-event-source="CompanyProfile" data-shared-object="SellerReview"><div class="icon icon-google circle circle-action social-share-google-js" title="Share on Google+"><i class="fa fa-google-plus-official" aria-hidden="true"></i></div></div><div class="btn-action clearfix" data-social-share-url="https://www.trustpilot.com/reviews/57c5e5e20000ff000981e1be" data-status="DanielleB gave The Logo Company 5 stars via #TrustpilotUS [Link]" data-event-source="CompanyProfile" data-shared-object="SellerReview"><div class="icon icon-twitter circle circle-action social-share-twitter-js" title="Share on Twitter"><i class="fa fa-twitter" aria-hidden="true"></i></div></div><div class="review-action-response" ><ul class="reporting hide" id="report_'+data.pid+'" style="display: none;"><li class="first">Dear Guest. You just clicked on Notify Compliance because you believe that this review is violating Trustpilot’s User Guidelines.<br><br><i>If you are a business user and you wish to report a review on your company profile, please do so on your business account. Don’t have an account? It’s free and easy to sign up.</i></li><li><label for="message">Please provide us with as much information as possible in the text field provided below (min. 50 characters).</label><div class="alert alert-warning hidden">Please use a minimum of 50 characters.</div><textarea name="message" id="message" class="form-control message" placeholder="Describe why you believe this review requires our Compliance Team’s attention. Does it contain e.g. defamatory statements, coarse language, or does it seem fake?"></textarea><input type="submit" value="Submit notification to Compliance" class="btn btn-primary btn-block btn-lg buttonsubmit-js"></li></ul><div class="find-useful hidden"></div></div></div></div></div>';
//str += '<div class="review-actions clearfix"><div class="btn-action clearfix "><div class="icon icon-thumbs-up circle-action blue-action" id="pressme_'+id+'" onclick="funn('+id+')"; title="Find useful" ><i class="fa fa-thumbs-up" aria-hidden="true"></i></div><div class="number-box" id="box_'+id+'" style="display:none"><div class="text useful-counter-js" id="val_'+id+'"></div></div></div><div class="btn-action clearfix" ><div class="icon icon-report circle-action notify" id='+id+' title="Notify Compliance" onclick="fun('+id+');"><i class="fa fa-flag" aria-hidden="true"></i></div></div><div class="btn-action clearfix" data-social-share-url="https://www.trustpilot.com/reviews/57c5e5e20000ff000981e1be" data-event-source="CompanyProfile" data-shared-object="SellerReview"><div class="icon icon-facebook circle circle-action social-share-facebook-js" title="Share on Facebook"><i class="fa fa-facebook" aria-hidden="true"></i></div></div><div class="btn-action clearfix" data-social-share-url="https://www.trustpilot.com/reviews/57c5e5e20000ff000981e1be" data-event-source="CompanyProfile" data-shared-object="SellerReview"><div class="icon icon-google circle circle-action social-share-google-js" title="Share on Google+"><i class="fa fa-google-plus-official" aria-hidden="true"></i></div></div><div class="btn-action clearfix" data-social-share-url="https://www.trustpilot.com/reviews/57c5e5e20000ff000981e1be" data-status="DanielleB gave The Logo Company 5 stars via #TrustpilotUS [Link]" data-event-source="CompanyProfile" data-shared-object="SellerReview"><div class="icon icon-twitter circle circle-action social-share-twitter-js" title="Share on Twitter"><i class="fa fa-twitter" aria-hidden="true"></i></div></div><div class="review-action-response" ><ul class="reporting hide" id="report_'+id+'" style="display: none;"><li class="first">Dear Guest./*'+username+'*/ You just clicked on Notify Compliance because you believe that this review is violating Trustpilot’s User Guidelines.<br><br><i>If you are a business user and you wish to report a review on your company profile, please do so on your business account. Don’t have an account? It’s free and easy to sign up.</i></li><li><label for="message">Please provide us with as much information as possible in the text field provided below (min. 50 characters).</label><div class="alert alert-warning hidden">Please use a minimum of 50 characters.</div><textarea name="message" id="message" class="form-control message" placeholder="Describe why you believe this review requires our Compliance Team’s attention. Does it contain e.g. defamatory statements, coarse language, or does it seem fake?"></textarea><input type="submit" value="Submit notification to Compliance" class="btn btn-primary btn-block btn-lg buttonsubmit-js"></li></ul><div class="find-useful hidden"></div></div></div></div></div>';
$(".reviews_container").html(str);
},
error: function(request, status, error) {
console.log(error);
}
});//inner ajax ends
}
}
});
}
Your second bout of ajax calls are done asynchronously so they will display as soon as the results are retunred. You are essentially firing all the ajax calls one after another without waiting for any results, and showing the results as they are answered by the server.

How to get ID of Button(onClick) which is created dynamically in javascript

How to get ID of button which is created by using following JS. I want to set Button's ID on
as label's text.
function addnewsubj(){
var a = $("#subjname").val();
if(a!=="" ){
$('.techsubj').append(
'<div class="row sub'+ a +'" id="sub'+ a +'">'+
'<div class="col-xs-6 col-md-4">'+
'<a href="#fourth" id="'+ a +'" class="btn btn-info" >'+ a +'</a>'+
'</div>'+
'<div class="col-xs-12 col-sm-6 col-md-8">'+
'<div class="progress">'+
'<div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%">'+
'<span class="sr-only">60% Complete (warning)</span>'+
'</div>'+
'</div>'+
'</div>'+
'</div>'
);
}
else{
alert("Text Box is empty");
}}
HTML
<label id="subjTitle"> </label>
You don't have a button anywhere. If you mean the anchor element that is styled as a button,
$('subjTitle').text($('.techsubj .btn').attr('id'))
Or, you could always explicitly create it with an ID, or best of all you could create the content as a DOM hierarchy instead of as a HTML source and just keep the reference to the "button" object around.
use jquery 'on' method for dynamic event. use this code:
$(document).on('click','.btn-info', function(){
$('#subjTitle').text($(this).attr('id'));
});
if you are using jquery below version 1.7 than you may use "live" or "delegate" for dynamic element.
Here is a little Example:
HTML :
<div id='th'></div>
Jquery:
$('#th').append('<div id="rock">this is Dynamo</div>');
alert($($('#th').children('div')[0]).attr('id'));
may it helps you!

Categories

Resources