Create dynamic id using purejs - javascript

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

Related

How to display XML with HTML input within main HTML tag in JavaScript?

Need to display xml data within html tags and also few html input field element within that XML data.
<xmlData><name><input type="text" /></name> </xmlData>
Expected Result : Display XML data with html input text field.
If you have the string in JavaScript then you can do either of these
const xmlString = `<xmlData><name><input type="text" /></name><text><textarea></textarea></text></xmlData>`;
document.querySelector("textarea").value = xmlString; // works even if there is a textarea in the data
document.getElementById("div1").textContent = xmlString;
const resultXmlText = new XmlBeautify().beautify(document.querySelector("textarea").value, {
indent: " ", //indent pattern like white spaces
useSelfClosingElement: false //true:use self-closing element when empty element.
});
document.getElementById("pre").textContent = resultXmlText
<script src="https://cdn.jsdelivr.net/npm/xml-beautify#1.2.3/dist/XmlBeautify.min.js"></script>
<textarea></textarea>
<hr/>
<div id="div1"></div>
<hr/>
<pre id="pre"></pre>
<hr/>

Why is my data-template not rendering new image with javascript?

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() ?

Create table inside html document from javascript using document.getelementbyid

I have a javascript function that extracts data from a database, puts it into an html table, and puts that table into an HTML page via a document.getElementById command. Everything works fine except when I load the HTML page, the data is not in the table. I am using the innerHTML property to put the table on the page. My question is, is this a valid way of populating a table to an HTML page? I have posted the relevant code below.
<div class="content mt-3">
<div class="animated fadeIn">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<strong class="card-title">Data Table</strong>
</div>
<div class="card-body">
<table id="results-data-table" class="table table-striped table-bordered">
<!-- I am trying to put the html here from javascript
</table>
</div>
</div>
</div>
</div>
</div><!-- .animated -->
</div><!-- .content -->
<script src="../controllers/query.js">getData()</script>
<script src="assets/js/vendor/jquery-2.1.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js"></script>
<script src="assets/js/plugins.js"></script>
<script src="assets/js/main.js"></script>
Javascript:
function getData() {
var sql = require("mssql");
var dbConfig={
server:"server",
database: "db",
user:"user",
password: "pw"
}
var conn = new sql.Connection(dbConfig);
var req = new sql.Request(conn);
conn.connect(function (err){
if (err) {
console.log(err);
return;
}
req.query("SELECT * FROM table",resultsCallback)
conn.close();
});
}
function resultsCallback (err, recordset) {
var tableify = require('tableify');
if (err) {
console.log(err);
}
else {
var html = tableify(recordset);
html = html.replace('<table>','');
html = html.replace('</table>','');
document.getElementById("results-data-table").innerHTML=html;
}
};
I can't comment to posts yet but i think you have a typo at the end of the select:
req.query("SELECT * FROM table,resultsCallback)
it should be:
req.query("SELECT * FROM table",resultsCallback)
Based on the statements you’ve written to strip out the table tags in the html variable, it looks as though that html variable is of type string. I ran some tests on the npm module you're using 'Tableify', and it's primary method does not return the elements in the form of DOM nodes. Therefore, you can't just inject the elements using .innerHTML in string form. That's mainly because the DOM expects the thing you're setting to the innerHTML isn't going to be other DOM nodes. JS expects you to use appendChild, or others means, to insert nodes as children of other DOM nodes.
Doing the few lines below should get you what you want. Firstly, don't strip out the table tag like you're doing, or the node will become invalid. Then run a createContextualFragment on the html variable. The result will be a document fragment, of which then you can run a querySelector on it to retrieve the first element, usually a tbody element, and then finally do an appendChild of that to your already existing table... for example
// create a DOM fragment from the string
var frag = document.createRange().createContextualFragment(html);
//get the first element from inside the table. This is usually a tbody, but you might want to make sure your Tableify is generating a tbody in yours.
var tableBody = frag.querySelector('tbody');
// append that node to the table DOM element
document.querySelector("#results-data-table").appendChild(tableBody);

How to render html partially inside div?

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>

How to handle spaces in div id in jquery

I am getting id of div from external source and in that spaces also coming in id , how to get the value of id. Here is my div example:
<div id="123456ABC" class="classname" onclick="javascript:AddValue(aa.value,'33',bb.value,'1000')"></div>
<div id="78904 bbc" class="classname1" onclick="javascript:AddValue(aa.value,'55',bb.value,'2000')"></div>
I need to get the class name from the id. Here is what I am doing:
function AddValue(aa, bb) {
var classOfDiv = $('#123456ABC').attr('class');
var classOfDivs = $('#8904 bbc').attr('class');
alert(classOfDiv);
alert(classOfDivs);
}
The first alert is working fine but second is not fetching a value. How can I handle this? All the values are dynamic.
Use $("div[id='78904 bbc']") to access element which has spaces in id, Try:
var classOfDiv = $("div[id='123456ABC']").attr('class');
var classOfDivs = $("div[id='78904 bbc']").attr('class');
alert(classOfDiv);
alert(classOfDivs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="123456ABC" class="classname" onclick="javascript:AddValue(aa.value,'33',bb.value,'1000')"></div>
<div id="78904 bbc" class="classname1" onclick="javascript:AddValue(aa.value,'55',bb.value,'2000')"></div>

Categories

Resources