How to hard code text which are coming from javascript messages - javascript

Our application is been internationalized and being changed to different languages. For that reason we have to hard code all the messages. How can we do that for messages in javascript ?
This is how we are doing in html messages.
<span th:text="#{listTable.deletedFromTable}">deleted</span>
How do we hard code for javascript messages.(update the table)
$('#TableUpdate-notification').html('<div class="alert"><p>Update the Table.</p></div>');

You will need to put the messages in the DOM from the start, but without displaying them. Put these texts in span tags each with a unique id and the th:text attribute -- you could add them at the end of your document:
<span id="alertUpdateTable" th:text="#{listTable.updateTable}"
style="display:none">Update the Table.</span>
This will ensure that your internationalisation module will do its magic also on this element, and the text will be translated, even though it is not displayed.
Then at the moment you want to use that alert, get that hidden text and inject it where you need it:
$('#TableUpdate-notification').html(
'<div class="alert"><p>' + $('#alertUpdateTable').html() + '</p></div>');
You asked for another variant of this, where you currently have:
$successSpan.html(tableItemCount + " item was deleted from the table.", 2000);
You would then add this content again as a non-displayed span with a placeholder for the count:
<span id="alertTableItemDeleted" th:text="#{listTable.itemDeleted}"
style="display:none">{1} item(s) were deleted from the table.</span>
You should make sure that your translations also use the placeholder.
Then use it as follows, replacing the placeholder at run-time:
$successSpan.html($('#alertTableItemDeleted').html().replace('{1}', tableItemCount));
You could make a function to deal with the replacement of such placeholders:
function getMsg(id) {
var txt = $('#' + id).html();
for (var i = 1; i < arguments.length; i++) {
txt = txt.replace('{' + i + '}', arguments[i]);
}
return txt;
}
And then the two examples would be written as follows:
$('#TableUpdate-notification').html(
'<div class="alert"><p>' + getMsg('alertUpdateTable') + '</p></div>');
$successSpan.html(getMsg('alertTableItemDeleted', tableItemCount));

Related

Cannot show TrustPilot HTML when inserted with JavaScript (jQuery)

If I added the TrustPilot html code directly on the HTML page, it works fine but I needed to insert it with jQuery. I see the HTML code when inserted but it's not displaying.
$(window).on('load', function () {
var el = $('#some-element');
el.html( trustPilotHtml() );
function trustPilotHtml() {
var str = "<div " +
"class='trustpilot-widget' " +
"data-locale='en-GB' " +
"data-template-id='123456' "+
"data-businessunit-id='123456' " +
"data-style-height='500px' " +
"data-style-width='100%' " +
"data-theme='light' " +
"data-stars='4,5' " +
"data-schema-type='Organization'>" +
"<a " +
"href='https://some-url.com' target='_blank'>Trustpilot</a> " +
"</div>";
return $(str);
}
});
Is the only way of getting the element to display properly is to directly inserted into the HTML without javascript?
No it's not the only way.
You should have a bootstrap script in your inside the HEAD part of your HTML (or close to it).
This script takes care of initializing all the widgets (TrustBoxes in Trustpilot lingo) that you have in your HTML.
Of cause that doesn't work if you are injecting the HTML dynmically, so it's also possible to call window.Trustpilot.loadFromElement(trustbox); yourself, when if you need to.
Here trustbox is a HTMLElement, you could get by using document.getElementById("some-element") or similar.
Reference: https://support.trustpilot.com/hc/articles/115011421468
The following worked for me on a product list page which returned filtered list via ajax
var element = document.getElementsByClassName("trustpilot-widget");
for(var i=0; i<element.length; i++) {
window.Trustpilot.loadFromElement(element[i]);
}
On the first page load all product reviews are displayed as expected, but if the page is updated via ajax call (using filters for example) the reviews are lost. Running the above code after ajax, reloads the reviews

Javascript: Add HTML to string - make a link and add it to output

New to javascript, how do I fix this problem I'm having?
I want to add an a tag to a string variable that i'm creating using a function.
The whole message (eg - "Your tutor is JOHN DOE. Contact them here: CONTACT FORM") Is added to the DOM with another function (which works).
When I run the script it outputs to the browser but the second part (makeLink()) doesnt work.
This is what I get: "Your tutor is JOHN DOE. Contact them here http://www.example.com" - Instead of the URL I want word CONTACT FORM which should be a link.
How do I do this?
I tried using link() Method, which also didnt work and had similar output.
I'll only include the relevant script below, the rest works fine...
function makeMessage(){
for(i in msgArr){
stringMSG += msgArr[i];
//do not add a comma after last item
if(i < msgArr.length - 1){
stringMSG += ', ';
}
}
var highRiskmsg = "Your tutor is " + stringMSG + ". Contact them here" + makeLink();
return highRiskmsg;
}
function makeLink() {
var contactLink = document.createElement("a");//create <a> tag
contactLink.setAttribute("id", "linkC");//set id att for <a> tag
contactLink.setAttribute("href", "http://www.example.com/contact.php");//set id att for <a> tag
var contactLinkTxt = document.createTextNode("CONTACT FORM");//new text node
contactLink.appendChild(contactLinkTxt);//append text as child of <a> tag
return contactLink;
}
It seems the problem is you are returning a DOM element from your makeLink() function, and this won't concat with the string as you expect.
You need to return a valid HTML string instead, such as: <a id=".." href="..">..</a>
The quickest way to fix your code would be just to change the return for the makeLink() function as follows:
return contactLink.outerHTML;
Using outerHTML will return the HTML string for the element, rather than the element itself.
Here is a working example
As an alternative to musefan's answer, you can return an element that contains both the message and link as nodes, instead of text.
function makeMessage(){
var highRiskmsg = "Your tutor is " + msgArr.join(',') + ". Contact them here";
var span = document.createElement('span');
span.appendChild(document.createTextNode(highRiskmsg));
span.appendChild(makeLink());
return span;
}
Fiddle

How to get the total of the list ordered, with Javascript

I'm making a code of a online delivery webpage, and I having a hard time trying to figure out how to output the total of the list ordered by the user.
function ListOrder(){
document.getElementById('order').innerHTML += "<div id=\"YourOrders\">" + + document.getElementById('FoodName').value + document.getElementById('quantity').value + document.getElementById('Totality').value + "</div><br>";}
Edited: I want to know how I can get the sum of the total price. So, I placed a parseInt between the document.getElementById('Totality').value . It looks like this now,
function ListOrder(){
document.getElementById('order').innerHTML += "<div id=\"YourOrders\">" + + document.getElementById('FoodName').value + document.getElementById('quantity').value + parseInt(document.getElementById('Totality').value) + "</div><br>";}
Can someone help me make a function or something for that? Javascript only, please. I'm still kinda new at it.
function ListOrder(){
document.getElementById('order').innerHTML +=
"<div id=\"YourOrders\">" +
parseInt(document.getElementById('FoodName').value) +
parseInt(document.getElementById('quantity').value) +
parseInt(document.getElementById('Totality').value) +
"</div><br>";
}
the kernel of your code should look like the following (double + operator deleted, reformatted):
function ListOrder(){
document.getElementById('order').innerHTML +=
"<div id=\"YourOrders\">" + (
document.getElementById('FoodName').value
+ document.getElementById('quantity').value
+ document.getElementById('Totality').value
)
+ "</div><br>"
;
}
You've phrased your question in a way that suggests you wish to output an order list assembled from the content of all (html) elements with certain ids.
this won't work reliably:
Ids should be document unique.
The Js functions you use do not iterate over lists.
instead, proceed along the following lines (which assume that you import jquery, a cross-browser dom-handling and ajax library (which you should use anyway :)):
function ListOrder(){
var e_orders = $("<div id=\"YourOrders\">");
$("#order").append(e_orders);
$(".FoodName").each ( function ( idx_fn, e_fn ) {
$(e_orders).append(
$("<div/>").append(
$(e_fn).val()
+ $(e_fn).nextAll('.quantity').val()
+ $(e_fn).nextAll('.Totality').val()
);
);
$(e_orders).append("<br>");
});
return e_orders;
}
The code template assumes that the source data are elements with value attributes being marked with css classes quantity, Totality and 'FoodName``, that these elements are siblings and unique within a container element for each item incl. quantity information. It should be flexible enough to be tailored to your actual needs and html structure.

How do dynamically create HTML via JavaScript using property names in Struts?

Here's my problem:
I have a JavaScript function inside of a JSP that looks like this:
<script type="text/javascript">
function generateTable()
{
var temp = '';
temp = temp + '<logic:iterate name="dataList" id="dto" indexId="dtoIndex" >';
temp = temp + '<logic:equal name="dtoIndex" value="0">';
temp = temp + '<thead>';
temp = temp + '<tr class="topexpression7"></tr></thead><tbody></logic:equal>';
temp = temp + '<tr>';
var propertyArray = new Array('"title"','"jDate"','"employeeId"','"employeeName"');
var arrayLength = propertyArray.length;
var html = '';
var i=0;
for (i=0; i<arrayLength; i++)
{
if (i == 2)
{
// left
html = html + '<logic:present name="dto" property=' + propertyArray[i] + '><td class="left"> <bean:write name="dto" property=' + propertyArray[i] + '/></td></logic:present>';
}
else if (i == 3)
{
// Only applies to this property
html = html + '<logic:present name="dto" property="employeeName">';
html = html + '<td class="left" style="white-space:nowrap;"> ';
html = html + '<nobr><bean:write name="dto" property="employeeName"/>';
html = html + '</nobr></td></logic:present>';
}
else
{
// center
html = html + '<logic:present name="dto" property=' + propertyArray[i] + '><td class="center"> <bean:write name="dto" property=' + propertyArray[i] + '/></td></logic:present>';
}
}
temp = temp + html + '</logic:iterate></tbody>';
// Write out the HTML
document.writeln(temp);
}
</script>
If I hard code the property like where (i == 3), it works fine. Renders as expected.
But by trying to parse a string dynamically (where i <> 3), the string var "html" is null every time. Admittedly, my JavaScript is average at best. I'm sure it's an easy fix, but darned if I can figure it out!
P.S. Long story as to why I'm going this route, and I'll spare you the story (you're welcome). I just want to know why the variable propertyArray[i] isn't working.
The JSP is rendered on the server and JavaScript on the client browser, but to render properly the JSP tags should be well formed, i.e. have all necessary attributes with valid values, begin and close tag, etc. But not all your tags are valid. First your JSP compiled on the server and it can't process the bad JSP tags. When i != 3 you have that bad JSP tags. When the JSP is compiled the JavaScript code is used like a content, it has less meaning for the JSP compiler because it is looking on the tags that correspond a JSP syntax. Looking by the eyes of the JSP compiler you'll see the logic:present tag has attribute property but has not a value because propertyArray[i] is not evaluated as a JSP expression, it simply breaks the tag boundary. So the Tag is not compiled properly. If you place JSP tags into JavaScript code make sure they're consistent.
propertyArray[i] is working; it's the rest of it that isn't (and won't).
JSP tags don't execute on the client side; HTML generated in JavaScript must not include JSP tags (unless you don't care if they don't run). Instead, the JavaScript itself must be generated using tags on the server side before it's sent to the browser.
In this case, however, it might be best to just render HTML returned from an Ajax request, though, depending on what you're really trying to do, or create it all in JSP (not JS), etc.

jQuery: trying hook a function to the onclick when page loads

I have seen a similar question, HERE and have tried that, but I can't seem to get it working.
Here is my code for dynamically generating table rows.
for (var contribution = 0; contribution < candidate.contributions.length - 1; contribution++) {
var id = candidate.contributions[contribution].donor_id;
var uid = candidate.contributions[contribution].user_id;
$("#history-table").append(
"<tr onclick='" + parent.viewEngine.pageChange('public-profile', 1, id, uid) + ";>" +
"<td class='img-cell'>" +
"<img class='profile-avatar-small' src='/uploads/profile-pictures/" +
candidate.contributions[contribution].image + "' alt='' /></td><td class=''>" +
"<h2>" + candidate.contributions[contribution].firstname +
" " + candidate.contributions[contribution].lastname + "</h2></a><br/><br/>" +
"<span class='contribution-description'>" + candidate.contributions[contribution].contribution_description + "</span></td>" +
"<td><h3>$" + formatCurrency(candidate.contributions[contribution].contribution_amount) + "</h3></td></tr>");
}
This still executes the click event as soon as the page loads, which is not the desired behavior. I need to be able to click the tr to execute the click event.
Pass the whole thing as a string:
"<tr onclick='parent.viewEngine.pageChange(\'public-profile\', 1, " + id + ", " + uid + ");>" // + (...)
But, as you are using jQuery, you should be attaching the click handler with .on().
(I really don't recommend using inline event handlers like that, especially when you're already using jQuery, but anyway...)
The problem is that you need the name of the function to end up in the string that you are passing to .append(), but you are simply calling the function and appending the result. Try this:
...
"<tr onclick='parent.viewEngine.pageChange(\"public-profile\", 1, " + id + "," + uid + ");'>" +
...
This creates a string that includes the name of the function and the first couple of parameters, but then adds the values of the id and uid variables from the current loop iteration such that the full string includes the appropriately formatted function name and parameters.
Note that the quotation marks around "public-profile" were single quotes but that wouldn't work because you've also used single quotes for your onclick='...', so you should use double-quotes but they need to be escaped because the entire string is in double-quotes.
I'm wondering if you might be better simplifying things a bit.
If your rows are being dynamically added, then try putting some kind of meta-data in the <tr> tag, e.g. something like this:
<tr id="id" name="uid">
Then try the following with your jQuery (v.1.7 required):
$('#history-table tr').on('click', function(){
parent.viewEngine.pageChange('public-profile', 1, this.id, this.name);
});
This will likely require modification depending on how your page rendering works but it's a lot cleaner and easier to read having been removed from your main table markup.
Well that's because you're executing the function, not concatenating it. Try:
onclick='parent.viewEngine.pageChange("public-profile", 1, id, uid);'
Take this ->
$("#contribution-" + uid).click(function(){
parent.viewEngine.pageChange('public-profile',1, id, uid);
});
And do two things:
1) Move it outside of the 'for' statement
As soon as the for statement is executed, the click function will be executed as well. The click function is not being supplied as a callback function in this for statement.
2) Change it to ->
$("tr[id^='contribution-'").on('click', function(){
var idString = $(this).attr("id").split("-"); //split the ID string on every hyphen
var uid = idString[1]; //our UID sits on the otherside of the hyphen, so we use [1] to selec it
//our UID will now be what we need. we also apply our click function to every anchor element that has an id beginning with 'contribution-'. should do the trick.
parent.viewEngine.pageChange('public-profile',1, id, uid);
});
This is my solution.

Categories

Resources