Each time a new message is sent, it is automatically displayed for each user. The message consists of the message, a timestamp, and the sender's profile picture. Using the HTML template, the message and timestamp displays but not the image.
HTML
<!--template for javascript incoming-->
<template id="incoming_template">
<div class="incoming_msg_img" data-template="temp_img">
</div>
<div class="received_msg">
<div class="received_withd_msg" aria-describedby="name">
<small id="name" data-template="sender">User</small>
<p data-template="temp_message"></p>
<span class="time_date" data-template="temp_time"></span></div>
</div>
</template>
JavaScript
$(function () {
// Get template
var template = $("#incoming_template").html();
var template_dom = $('<div/>').append(template);
// Create a new row from the template
var $row = $(template);
var img = "<img src=../static/avatars/beard.png>";
// Add data to the row
$row.find("p[data-template='temp_message']").text(data.msg);
$row.find("span[data-template='temp_time']").text(data.timestamp);
$row.find("small[data-template='sender']").text(data.sender);
$row.find("div[data-template='temp_img']").html(img);
// Add the row to the table
$("#newmsg").append($row);
updateScroll();
});
Currently, you are wrapping some HTML string in a jQuery object. You need to temporarily create a DOM object out of your template HTML so that the jquery find function can properly find the elements inside a DOM tree. See revisions below:
// Get template
var template = $("#incoming_template").html();
// Add this line to your code
var template_dom = $('<div/>').append(template);
// Create a new row from the template
var $row = $(template_dom);
Then change this line:
$row.find("div[data-template='temp_img']").text(img);
To this:
$row.find("div[data-template='temp_img']").html(img);
Since you are appending a markup and not some text.
Read more here: What is the difference between jQuery: text() and html() ?
Related
I have a div and I want to set some text inside this div. Problem is my text contains HTML elements and I don't want all these elements to be rendered. I mean some elements must rendered as HTML.
Is there any way to create a div content like this?
I want to create a div element like below;
<div id="bodyContent">
</div>
Setting with html method is not working.
var myHTMLContentPart1 = "<HTML><BODY>";
var myHTMLContentPart2 = "<span>hello</span>";
var myHTMLContentPart3 = "</BODY></HTML>";
$("#bodyContent").html(?);
EDIT:
I recommend you to use regex to remove html or body tags, also you can add any tag that you want to remove like this <\/?tagname>
html = '<html><body><span>Some Text</span></body></html>';
clean = html.replace(/<\/?html>|<\/?body>/g, '');
console.log(clean);
// For your code
var myHTMLContentPart1 = "<HTML><BODY>";
var myHTMLContentPart2 = "<span>hello</span>";
var myHTMLContentPart3 = "</BODY></HTML>";
var html = myHTMLContentPart1 + myHTMLContentPart2 + myHTMLContentPart3;
clean = html.replace(/<\/?html>|<\/?body>/g, '');
$("#bodyContent").html(clean);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="bodyContent">
</div>
For a project to make communications clearer for a website, I have to pull the messages using regex (Why? Because the message is commented out. With normal document.getElement I can't reach the message. But with the Regex mentioned below i can.)
I am trying to get a value using this expression:
\s*<td width="61%"class="valorCampoSinTamFijoPeque">(.|\n)*?<\/td>
How i use this expression:
var pulledmessage = /\s*<td width="61%"class="valorCampoSinTamFijoPeque">(.|\n)*?<\/td>/.exec(htmlDoc);
The above expression gives me NULL when i console.log() it. My guess is that the htmlDoc format that i supply the regex is not working. I just have no clue how to make it so the value does get pulled.
What i use to parse HTML:
var html1 = httpGet(messages);
parser = new DOMParser();
htmlDoc = parser.parseFromString(html1,"text/html");
The result I want to get:
<td width="61%"class="valorCampoSinTamFijoPeque"><b>D.</b> De:
Information, Information.
Information, Information
Para: Information
CC: Information
Alot of text here ............
</td>
I edited the above value to remove personal information.
html1 contains a full HTML page with the information required.
New attempt. Seeing how the td you need is commented out, remove all HTML comment delimiters from the loaded HTML file before parsing the document. This will result in the td being rendered in the document and you can use innerHTML to get the message content.
const
documentString = `
<!doctype html>
<html>
<body>
<div class="valorCampoSinTamFijoPeque">1</div>
<div class="valorCampoSinTamFijoPeque">2</div>
<div class="valorCampoSinTamFijoPeque">3</div>
<div class="valorCampoSinTamFijoPeque">4</div>
<div class="valorCampoSinTamFijoPeque">5</div>
<div class="valorCampoSinTamFijoPeque">6</div>
<!--<div class="valorCampoSinTamFijoPeque"><b>D.</b> De: Information, Information. Information, Information Para: Information CC: Information Alot of text here ............</div>-->
<div class="valorCampoSinTamFijoPeque">8</div>
</body>
</html>`,
outputElement = document.getElementById('output');
debugger;
const
// Remove all comment delimiters from the input string.
cleanupDocString = documentString.replace(/(?:<!--|-->)/gm, '');
// Create a parser and construct a document based on the string. It should
// output 8 divs.
parser = new DOMParser();
htmlDoc = parser.parseFromString(cleanupDocString,"text/html");
const
// Get the 7th div with the class name from the parsed document.
element = htmlDoc.getElementsByClassName('valorCampoSinTamFijoPeque')[6];
// Log the element found in the parsed document.
console.log(element);
// Log the content from the element.
console.log(element.innerHTML);
<div id="output"></div>
There is no need for a regex, native JS has your back!
const
documentString = '<!doctype html><html><body><div class="valorCampoSinTamFijoPeque">1</div><div class="valorCampoSinTamFijoPeque">2</div><div class="valorCampoSinTamFijoPeque">3</div><div class="valorCampoSinTamFijoPeque">4</div><div class="valorCampoSinTamFijoPeque">5</div><div class="valorCampoSinTamFijoPeque">6</div><div class="valorCampoSinTamFijoPeque">7<!--<b>D.</b> De: Information, Information. Information, Information Para: Information CC: Information Alot of text here ............--></div><div class="valorCampoSinTamFijoPeque">8</div></body></html>',
outputElement = document.getElementById('output');
function getCommentText(element) {
for (var index=0; index<element.childNodes.length;index++){
const
node = element.childNodes[index];
if (node.nodeType === Node.COMMENT_NODE) {
return node.data;
}
}
}
// Create a parser and construct a document based on the string. It should
// output 8 divs.
parser = new DOMParser();
htmlDoc = parser.parseFromString(documentString,"text/html");
const
// Get the 7th div with the class name from the parsed document.
element = htmlDoc.getElementsByClassName('valorCampoSinTamFijoPeque')[6];
// Replace the HTML of the element with the content of the comment.
element.innerHTML = getCommentText(element);
// The the inner HTML of the parsed document's body and place it inside the output
// element in the page that is visible in the user agent. The 7th div should not
// contain a number but the text that was originally in the comment.
outputElement.innerHTML = htmlDoc.body.innerHTML;
<div id="output"></div>
I am rather new to JavaScript. In my experimentation with some sample code, I have created an html file which contains a table. In one of the table data fields I have a text type field. Is there a way to make a button that inserts a pre-defined template for entry that allows for manipulation? aka I press a button "money" that inputs an additional formatted text to "$0.00".
so for example
function input_button(){
var template = "$0.00"
var my_txt = document.getElementById("money");
my_txt.value += Template;
On a side note, what if I wanted to use subscript and superscript? I have tried utilizing the .sup() and .sub() methods, but it just inserts the tags and doesn't alter the aesthetics of the text. ( so in the table, it looks like
<sub> things to be subscript </sub>
opposed to
things to be subscript
I'm not familiar with any way to template text formats, so you might just have to hard code in the logic. As to your second question, when you use the .sup and .sub methods, are you inserting the result in the inner html? For example:
function helloWorldSuper(){
var str = "Hello World";
var result = str.sup();
document.getElementById("tableCell").innerHTML = result;
}
To apply a mask to the input field in order to auto-format values with a template you will need to listen to input key press events and handle according to your mask. There are some scripts that already do this, like Masked Input Plugin for jQuery.
If you want the input text to just have $0.00 as an initial value, it's quite easy to do.
You can create and insert a row into the table via JavaScript like this:
<html>
<body>
<button id="insertRowButton">Insert</button>
<table>
<thead>
<tr><th>Text</th><th>Input</th></tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
<script>
(function() {
// Elements used
var tableBody = document.getElementById('tableBody'),
insertRowButton = document.getElementById('insertRowButton');
// Create a new row template
function createRow() {
var tr = document.createElement('tr'),
tdText = document.createElement('td'),
tdInput = document.createElement('td'),
sub = document.createElement('sub'),
input = document.createElement('input'),
text = document.createTextNode('This is a text node '),
subscriptText = document.createTextNode('with subscript');
sub.appendChild(subscriptText);
tdText.appendChild(text);
tdText.appendChild(sub);
input.value = '$0.00';
tdInput.appendChild(input);
tr.appendChild(tdText);
tr.appendChild(tdInput);
return tr;
}
// Insert a new row into table
function insertRow() {
var tr = createRow();
tableBody.appendChild(tr);
}
// Bind events
insertRowButton.addEventListener('click', insertRow);
}());
</script>
</body>
</html>
Here is it at JSFiddle: http://jsfiddle.net/ck7qargw/
I'm a little confused but I'm making the assumption that you are trying to add sup/sub script via innerHTML?
var template = "<span class='supStyle'>$0.00</span>"
CSS:
.supStyle{vertical-align:top;font-size:smaller;}
Or, you can use a forloop:
mySup = document.getElementsByClassName("supStyle");
for (var i=0;i<mySup.length;i++)
{
mySup[i].style.verticalAlign = "sub";
mySup[i].style.fontSize = "smaller";
}
Using purejs, i want to create dynamic id to each rendering element.
In this code i need to set id for each a tag. This 'a' tag will create depends on the jsonData.
<!-- HTML template -->
<div id="template" class="template">
Hello <a></a>
</div>
<!-- result place -->
<div id="display" class="result"></div>
<script>
var jsonData = {data:[{who:'Google!',site:'http://www.google.com/'},{who:'Yahoo!',site:'http://www.yahoo.com/'}]};
//select the template
$('#template')
//map the HTML with the JSON data
.directives({
'div a':{
'd<-data':{
'.':'d.who',
'#href':'d.site'
}
}
})
//generate the new HTML
.render(jsonData)
//place the result in the DOM, using any jQuery command
.appendTo('#display');
</script>
To set dynamic id use ".pos" tag. This ".pos" will having the position of the data in an array.
//select the template
$('#template')
//map the HTML with the JSON data
.directives({
'div a':{
'd<-data':{
'#id':'xyz_#{d.pos}',
'.':'d.who',
'#href':'d.site'
}
}
})
//generate the new HTML
.render(jsonData)
//place the result in the DOM, using any jQuery command
.appendTo('#display');
I have a div containg a few dynamically generated dropdowns.
I want to clone this and add it underneath the original. The code for the original is:
<div id="subjectselectiondiv" style="width:inherit;">
<h4>Select the subjects that you are able to tutor</h4>
<div id='choices'>
<script type="text/javascript">
var doc = document.getElementById("choices");
var subj_div = document.createElement('div');
subj_div.setAttribute('class', 'selectSearchBar');
subj_div.innerHTML = '<select id="level'+counter+'" name="level'+counter+'" class="selectSearchBar"><?php echo "<option>Level</option>"; while($row = mysqli_fetch_array($result_level, MYSQLI_ASSOC)){echo "<option value=".$row['id'].">".$row['level']."</option>";}?></select><div id="subject'+counter+'" style="display:inline;">sBar2</div><div id="topic'+counter+'" style="display:inline;">sbar3</div>';
doc.appendChild(subj_div);
</script>
Add another subject
</div>
I thought that the function Repeat() would work with:
function Repeat(){
counter++;
$('#choices').clone().appendTo('#subjectselectdiv');
event.preventDefault();
}
but this isnt working - am I missing something?
Thanks
Name mismatches:
<div id="subjectselectiondiv" style="width:inherit;">
^^^^^^
$('#choices').clone().appendTo('#subjectselectdiv');
^^^
What you're attempting to append to doesn't exist. Most likely if you'd bothered checking your javascript console, you'd have seen the warnings/errors about the non-existing element.