Converting String to HTML - string to " a href" element - javascript

Hello I am having some trouble getting some HTML links to add to my HTML page. I have tried searching around but nothing has helped thus far.
My page will initially load a snippet:
<div style="display: inline-block; color: rgb(0, 255, 144)">Roster: </div>
<span id="teamRoster"></span>
<br />
Which appears like Roster: in the View
Right now my snippet has been modified to add names:
var rosterListings = "";
for (var i = 0; i < teamRoster.length; i++) {
rosterListings = rosterListings + teamRoster[i] + ", ";
}
$("#teamRoster").text(rosterListings);
Which will update my View to Roster: John, Frank, Susan, ect..
However, I am trying to now add <a href> tag's around each person and turn them all into actual links. My attempt looks like this
var rosterListings = "";
for (var i = 0; i < teamRoster.length; i++) {
rosterListings = rosterListings + " <a href='" + idList[i] + "'>" + teamRoster[i] + "</a>,";
}
$("#teamRoster").text(rosterListings);
which displays as
Roster: <a href='#'>John</a>, <a href='#'>Frank</a>, ect..
I understand why this occurring since I am setting actual text/strings, but is there a way to convert this string into HTML elements? I have tried a few $.parseHTML code snippets that I found from Googling but I must be implementing them all wrong.. :(
Any help appreciated, Thank you!

Well, solution is quite obvious
Just replace
$("#teamRoster").text(rosterListings);
With:
$("#teamRoster").html(rosterListings);
Because if you use it as a text then it will treat it as the text and if you write html then it will treat it as a html

The problem is that you're using .text(), which will insert only text into the span, as seen here.
You need to use .html() if you want what is inserted to actually render as HTML.
So, try this:
$("#teamRoster").html(rosterListings);
Demo
Also note that the way you've set up your for loop causes an extra comma to be placed at the end of the list; I've fixed that here by checking whether it's the last element:
if (i !== teamRoster.length - 1) {
rosterListings = rosterListings + " <a href='" + idList[i] + "'>" + teamRoster[i] + "</a>,";
} else {
rosterListings = rosterListings + " and <a href='" + idList[i] + "'>" + teamRoster[i] + "</a>.";
}

As Just code points out, you want to use the html method, not the text method. html() is jQuery's wrapper for innerHTML, which injects the string as html.
Here is a jsFiddle showing the difference:
http://jsfiddle.net/89nxt/
$("#teamRosterHtml").html("<a href='#'>John</a> <a href='#'>Frank</a>");
$("#teamRosterText").text("<a href='#'>John</a> <a href='#'>Frank</a>");

Related

addeventlistener to indexed element

I have a list of elements. However, the length of this list varies between trials. For example, sometimes there are 6 elements and sometimes there are 8. The exact number is detailed in an external metadata.
To display this variable list, I've written:
var html = '';
html += '<div id="button' + ind + '" class="buttons">';
html += '<p>' + name + '</p></div>';
display_element.innerHTML = html;
If I were to 'inspect' the elements in my browser, they would appear to have IDs of button0.buttons, button1.buttons, etc.
Now I am trying to attach event listeners to each element but my code is not working so far. Different forms of broken code below:
document.getElementById("button' + ind + '").addEventListener("click", foo);
$("#button' + ind + '").click(foo);
document.getElementById("button").addEventListener("click", foo);
$("#button").click(foo);
Any help would be very appreciated! Thanks.
You wrong at concat string update it as
document.getElementById("button" + ind).addEventListener("click", foo);
var html = '';
var ind = 1;
var display_element = document.getElementById("test");
html += '<div id="button' + ind + '" class="buttons">';
html += '<p>' + name + '</p></div>';
display_element.innerHTML = html;
document.getElementById("button" + ind).addEventListener("click", foo);
function foo(){
alert('click');
}
<div id="test"></div>
Use "document.getElementsByClassName" get all botton elements then foreach to add click function.
document.getElementsByClassName('buttons').map( element => { element.addEventListener("click", foo) })
To answer the question of why neither of those uses of document.getElementById() are working for you, you are mixing your quotes incorrectly. "button' + ind '" evaluates to exactly that, rather than evaluating to "button0", "button1", etc. To make your code more readable, and to avoid similar quote mixing issues, I would recommend looking into template literals https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
With modern JS if you want to execute the same function you won't require to add an id to each button.
Just use the class added to the buttons like this:
document.querySelectorAll('.buttons').forEach(button => {
button.addEventListener('click',foo);
});
Then use the event parameter in that function to get the target node & execute whatever you want. You can also add data attributes in those buttons to use while executing that function.

Concatenate javascript string and variable in an echo statement

I want to limit the size of a paragraph of text. The wrapper div has a dynamically created ID and the paragraph text is also dynamically inserted. The HTML and JavaScript are in the same file.
The HTML
echo"
...
<div id ='subTextWrapper$sub_id' >
<p>$submission_text</p>
</div>
...";
The JavaScript:
echo"
<script>
...
var submissionId = $sub_id;
//Limit size of a submission if too long and show a link to read more
var submissionString = $('#subTextWrapper' + submissionId).html();
if (submissionString.split(' ').length > 50) {
$('#subTextWrapper' + submissionId).html(submissionString.split(' ').slice(0, 50).join(' ')
+ ' ... '
+ `<a class='read-more' + submissionId>Read more</a>`);
}
$('a.read-more' + submissionId).click(function () {
$('#subTextWrapper' + submissionId).html(submissionString);
});
...
</script>";
In the if statement above I want to concatenate the class name read-more with ``` the variable submissionId:
`<a class='read-more' + submissionId>Read more</a>`
This doesn't seem to work. I am not an expert in JS, so any help would be appreciated. Just a note, when I remove the variable submissionId then it works, but obviously it expands all my dynamically created submissions.
You concatenation seems wrong.
What you are currently inserting is exactly what you see as string:
<a class='read-more' + submissionId>Read more</a>
and not the value of submissionId. Since you are not handling the two different delimiters correctly. You have ` enclosing the whole a element and ' enclosing the class. You are closing the class before adding the submissionId and not closing the main literal to acutally include the value of submissionId
.
You can fix it like (if submissionId is a string):
`<a class='read-more` + submissionId.trim() + `'>Read more</a>`
or
`<a class='read-more#Sub.'>Read more</a>`.replace('#Sub.', submissionId.trim())
You could also use an array to build your string to avoid the different delimiters:
//var submissionId = 1234;
var tString = [];
tString.push("<a class='read-more"); //REM: Open the class attribute and not closing it since submissionId is part of the class
tString.push(submissionId); //REM: Adding the value of submissionId
tString.push("'>Read more</a>"); //REM: Closing the class attribute
console.log(tString.join('')); //-> <a class='read-more1234'>Read more</a>
Since submissionId looks like an id/number to me, please be aware that classnames shall not start with digits.
Furthermore if you want to limit the characters of a string you could use String.prototype.substring() instead:
submissionString.substring(0, 50);
would it not work like so.
echo"
<script>
//Limit size of a submission if too long and show a link to read more
var submissionString = $('#subTextWrapper' + submissionId).html();
if (submissionString.split(' ').length > 50) {
$('#subTextWrapper' + submissionId).html(submissionString.split(' ').slice(0,
50).join(' ')
+ ' ... '
+ `<a class='read-more' + submissionId>Read more</a>`);
}
$('a.read-more'$sub_id).click(function () {
$('#subTextWrapper'$sub_id).html(submissionString);
});
...
</script>";
or you could also concatenate like so
$('a.read-more'".$sub_id.")

JavaScript appendChild text node doesn't break line

a JavaScript n00b here...
I'm generating some html code in javascript, that is going to be displayed as code via the prism HTML markup plugin. The code is dynamically added to a <pre> tag on a button click.
My javascript code is as below. It is the text in line 2, where I need a line break. I have tried /n but that doesn't work it just makes a space.
var startLabelTag = document.createTextNode("text goes here");
startLabelTag.nodeValue = "<label><strong>" + elementNameFinal + "</strong></label>LINEBREAK HERE<select id='dropdownmenu' class='Custom_" + fieldNameFinal + "' onchange='selectChanged('#field[" + fieldNameFinal + "]',this.value);'>";
document.getElementById("dropdown-code").appendChild(startLabelTag);
Below is the text string I'm trying to create, where a line break is made where the text LINEBREAK HERE is.
<label><strong>" + elementNameFinal + "</strong></label>LINEBREAK HERE<select id='dropdownmenu' class='Custom_" + fieldNameFinal + "' onchange='selectChanged('#field[" + fieldNameFinal + "]',this.value);'>
Is it something like this you are looking for?
By using String.fromCharCode(10) you can insert a line break and with the pre tag (or div having white-space: pre-wrap) the line break will be visible/shown.
var elementNameFinal = "elementname", fieldNameFinal = "fieldname";
var startLabelTag = document.createTextNode("text goes here");
startLabelTag.nodeValue = "<label><strong>" + elementNameFinal + "</strong></label>" + String.fromCharCode(10) + "<select id='dropdownmenu' class='Custom_" + fieldNameFinal + "' onchange='selectChanged('#field[" + fieldNameFinal + "]',this.value);'>";
document.getElementById("dropdown-code").appendChild(startLabelTag);
<pre id="dropdown-code"></pre>
Side note
You can of course use a div as well, having the CSS rule Niet the Dark Absol suggested.
<div id="dropdown-code"></div>
#dropdown-code {
white-space: pre-wrap;
}
Add white-space: pre-wrap to the container's CSS.
After all, if you type a newline in your HTML source, do you get a blank line in the result? Nope. Not without making whitespace significant through CSS.

How to hard code text which are coming from javascript messages

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));

why is this javascript not working

I'm trying to build a function for adding bread crumbs to my site's navigation. However, right now I have two problems. 1) For some reason the crumb array only holds 2 crumbs at a time, and 2), even though the html elements are stored in the crumbs array, only the new crumb's HTML is rendered. The other crumb renders as:
[object HTMLLIElement]
// script
function add_crumb(name) {
// get current bread crumbs
var crumbs = $('#breadcrumbs ul li').toArray();
// no current bread crumbs, so we don't need an arrow image
if (crumbs.length == 0) {
var new_crumb = "<li class='crumb' style='display:inline'> " + name + " </li>";
} else {
var new_crumb = "<li class='crumb' style='display:inline'><img class='bc_arrow' src='images/icons/breadcrumb_arrow.png' width='19' height='18'> " + name + "</li>";
}
// add new bread crumb to array
crumbs.push(new_crumb);
// render
$('#breadcrumbs').html('<ul>' + crumbs.join('') + '</ul>');
}
Anyways, I've side stepped the second problem by creating a new blank array and calling .innerHTML on each element (even though I don't understand why I have to do this since jQuery's site says the elements are stored like so:
[<li id="foo">, <li id="bar">]
But if someone could please help me figure out why it's only storing two bread crumbs at a time, I would really, really appreciate it.
Thanks
HTML Element Objects are not strings, you cannot simply concat them to a string using .join. Try appending them.
$('#breadcrumbs').html('<ul />').find("ul").append(crumbs);
$('#breadcrumbs ul li').toArray(); gives you an array of HTMLLIElements.
You should take a different approach altogether. No need for any arrays:
if($('#breadcrumbs ul li').length){
$('#breadcrumbs ul').append(
"<li class='crumb' style='display:inline'>"
+ name +
"</li>");
}else{
$('#breadcrumbs ul').append(
"<li class='crumb' style='display:inline'>"
+ "<img class='bc_arrow' src='images/icons/breadcrumb_arrow.png' width='19' height='18'>" +
+ name +
"</li>");
}

Categories

Resources