How can i print variable to formatted html in the javascript? - javascript

How can I print variable to formatted html in the javascript?
I would like to display as a hyperlink:
The result i would like to have:
test
-------Code---------
This is the javascript function code:
function fetchComments(leaveRequestId) {
$('#existingComments').html(lang_Loading);
params = 'leaveRequestId=' + leaveRequestId;
$.ajax({
type: 'GET',
url: getCommentsUrl,
data: params,
dataType: 'json',
success: function(data) {
var count = data.length;
var html = '';
var rows = 0;
$('#existingComments').html('');
if (count > 0) {
html = "<table class='table'><tr><th>"+lang_Date+"</th><th>"+lang_Time+"</th><th>"+lang_Author+"</th><th>"+lang_Comment+"</th></tr>";
for (var i = 0; i < count; i++) {
var css = "odd";
rows++;
if (rows % 2) {
css = "even";
}
var comment = $('<div/>').text(data[i]['comments']).html();
html = html + '<tr class="' + css + '"><td>'+data[i]['date']+'</td><td>'+data[i]['time']+'</td><td>'
+data[i]['author']+'</td><td>'+comment+'</td></tr>';
}
html = html + '</table>';
} else {
}
$('#existingComments').append(html);
}
});
}

I am also not sure what exactly you want, but I think you want to add some anchor tag using JavaScript and it should be rendered as HTML code, not as plain text.
Then you can do it like this.
<!DOCTYPE html>
<html>
<body>
<div id="demo"> </div>
<button onclick="myFunction()"> Click here </button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = 'Test';
}
</script>
</body>
</html>

This should work.
document.getElementById("displayed").innerHTML = document.getElementById("displayed").innerHTML.replaceAll("&", "&").replaceAll("<", "<")
<code id="displayed">test</code>
<button onclick="document.getElementById('displayed').innerHTML = '<a href=\'#\'>test</a>'">Click To Change Into Hyperlink</button>
References
See Display HTML snippets in HTML for more information on displaying html on webpages.

Related

How to create a button to add URL links in the form

Does anyone know how to add like a link button into a form? For example, a user clicks a + button and they can add an URL. They can add another URL if they wish and remove any links if required. Would be good to have validation for links as well.
I know for validation of the URL I can use "Check if a JavaScript string is a URL", but will need something that will validate all links if multiple have been added.
The best way to explain what I am trying to do is by looking at "Can I insert a hyperlink in my form?" in the form builder.
I just want to add links, and I don't need to display text or anything like that.
Is this what are you looking for?
Your question is a bit unclear.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
let i = 0;
let ii = 0;
function isURL(s) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/
return regexp.test(s);
}
function removeLink(id, iid) {
console.log(id);
console.log(iid);
$(id).remove();
$(iid).remove();
return false;
}
function addLink(id) {
var input = prompt("Enter the link", "https://www.example.com");
var valid = isURL(input);
console.log(valid);
if(valid) {
var element = '<br><a id="_' + i + '" href="' + input + '">Link</a>';
console.log(element);
$(id).append(element);
let d = "'#_" + i + "'";
let dd = "'#__" + ii + "'";
let elment = ' <button type="button" id="__' + ii + '" onclick="removeLink(' + d + ', ' + dd + ')">Remove it!</button>';
$(id).append(elment);
console.log(elment);
i = i + 1;
ii = ii + 1;
}
else {
alert("The URL that you have entred is wrong.");
}
return false;
}
</script>
</head>
<body>
<form id="_form" method="POST">
<button type="button" onclick="addLink('#_form')">Add link</button>
</form>
</body>
</html>
Try it here: https://codepen.io/marchmello/pen/ZEGjMyR?editors=1000
What about DOM - not using longer form, so using URL as link text too.
function addUrl(e) {
var f = e.form;
var a = document.createElement("A");
a.href = e.value; // link URL
a.textContent = e.value; // link text
f.appendChild(a);
var x = document.createElement("INPUT");
x.type = "button";
x.value = "X";
x.onclick = remove;
f.appendChild(x);
f.appendChild(document.createElement("BR"));
}
function remove() {
var el = this, // button
parent = el.parentNode, // a must for remove
a = el.previousElementSibling; // anchor
if(el.nextSibling.tagName == 'BR') parent.removeChild(el.nextSibling);
parent.removeChild(el);
parent.removeChild(a);
}
<form>
<input name="url" size="50">
<input type="button" value="Add" onclick="addUrl(this.form.url)"><br>
</form>

Not able to display all rows dynamically

i have 7 team member and im just able to display 1 of them in id demo, how can i display all my team members? PFB HTML code and javascript one what im using for the same:
<div class="col-lg-3 mb-0" style="display: flex;align-items: center;">
<div class="popup" onclick="myFunction()"><h6>My team</h6>
<span class="popuptext" id="myPopup">My team members:<br><h7 id="demo"></h7><br></span>
</div>
</div>
</div>
<ol class="breadcrumb"></ol>
<script>
// When the user clicks on <div>, open the popup
function myFunction() {
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
var data1 = "TEAMSEARCH";
//alert(data1);
$.ajax({
url : 'TeamAssignment',
type : 'POST',
data : {
data1 : data1
},
success : function(result) {
var memberList = $.parseJSON(result);
//alert ( "Returned rows " + memberList.length);
for (var i = 0; i < memberList.length; i++)
{
console.log(memberList[i].fullName );
document.getElementById("demo").innerHTML = memberList[i].fullName;
}
}
});
}
</script>
document.getElementById("demo").innerHTML = memberList[i].fullName
Each iteration of the loop rewrites the entire innerHTML of demo. You probably want something like document.getElementById("demo").innerHTML += '<li>' + memberList[i].fullName + '</li>'
the += is the actually important part.
You repeatedly overwrite the demo innerHTML. You should make the assignment right after the for loop.
try something like this:
var members = '';
for (var i = 0; i < memberList.length; i++) {
console.log(memberList[i].fullName );
members += memberList[i].fullName;
}
document.getElementById("demo").innerHTML = members;
You can also use below one:
var memberList = $.parseJSON(result);
$("#demo").html('') // here just make empty innetHTML
for(var member of memberList)
$("#demo").append('<li>' + member.fullName + '</li>') // here appending html string of each member

How to sort AJAX results using toggle button

I have made an AJAX request that fetches completed Ebay auction results using Ebay's API (Finding Service). It works, producing the desired results, but now I am a stuck on how best to filter those results (in my case, using a button) by price, date of sale, etc.
For example: I have the variable url which has the filter url += "&sortOrder=StartTimeNewest";. I would like a button to toggle between that filter and url += "&sortOrder=StartTimeOldest"; using a click event.
I am a student, and pretty inexperienced when it comes to JS/frameworks...and so far have not had much luck figuring out the best way to do this aside from duplicating my entire code from ebay.js and altering it slightly for each filter I would like to apply.
For example: I can create different variables like url1, url2 and so on that have the filters I want, calling them from a different ajax requests attached to the buttons...
...but I'm sure there is a better and simpler way to do this without being so repetitive and would appreciate any help pointing me in the right direction.
Ebay.js
$(window).load(function() {
$('form[role="search"]').submit(function(ev) {
ev.preventDefault();
var searchstring = $('input[type="text"]', this).val();
var url = "https://svcs.ebay.com/services/search/FindingService/v1";
url += "?OPERATION-NAME=findCompletedItems";
url += "&SERVICE-VERSION=1.13.0";
url += "&SERVICE-NAME=FindingService";
url += "&SECURITY-APPNAME=BrandonE-DigIt-PRD-5cd429718-3d6a116b";
url += "&GLOBAL-ID=EBAY-US";
url += "&RESPONSE-DATA-FORMAT=JSON";
url += "&REST-PAYLOAD";
url += "&itemFilter(0).name=MinPrice";
url += "&itemFilter(0).value=7.00";
url += "&itemFilter(0).paramName=Currency";
url += "&itemFilter(0).paramValue=USD";
url += "&paginationInput.pageNumber=1";
url += "&paginationInput.entriesPerPage=50";
url += "&keywords=" + searchstring;
url += "&sortOrder=StartTimeNewest";
url += "&categoryId=176985";
$.ajax({
type: "GET",
url: url,
dataType: "jsonp",
success: function(res){
console.log(res);
var items = res.findCompletedItemsResponse[0].searchResult[0].item;
var ins = "";
for (var i = 0; i < items.length; i++){
ins += "<div>";
ins += "<img src='" + items[i].galleryURL + " '/>";
ins += " " + items[i].title + " - ";
ins += "Sold for $" + items[i].sellingStatus[0].currentPrice[0].__value__;
ins += "</div><br />";
};
$('.results').html(ins);
}
});
});
});
HTML:
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button id="mainbtn" type="submit" class="btn btn-default">Search</button>
</form>
<div class="filters col-xs-12 col-md-10 col-offset-md-1">
<!-- TOGGLE BUTTONS WILL ALLOW RESULTS TO BE SORTED. -->
<button type="button" class="btn btn-info btn-sm date-btn">date</button>
<button type="button" class="btn btn-info btn-sm price-btn">price</button>
</div>
<br />
<div class="index col-xs-12 col-md-10 col-offset-md-1">
<p class="restitle">results:</p><br />
<div class="results"></div>
</div>
Per our comments, I created a simple class that will generate the url for you.
Go ahead and tweek it to get the correct values in there. Hopefully this helps!
I added comments in the code but lmk if you have any questions.
$(function() {
// invoke click event
$("[data-filter]").off();
$("[data-filter]").on("click", function() {
let $this = $(this);
let data = $this.data();
// toggle value
if (data.value == false) {
$(this).data("value", true);
} else {
$(this).data("value", false);
}
// create class
let url = new buildfindCompletedItemsUrl();
// get the sort order
url.getSortOrder();
// build the url
let ajaxUrl = url.build();
// get the results
GetFilteredResults(ajaxUrl, function(results) {
$("body").append($("<p />", {
text: results
}));
})
});
})
// class with contructor
function buildfindCompletedItemsUrl() {
this.url = "https://svcs.ebay.com/services/search/FindingService/v1";
this.defaultUrlParams = {
"OPERATION-NAME": "findCompletedItems",
"SERVICE-VERSION": "1.13.0",
"SERVICE-NAME": "FindingService",
"SECURITY-APPNAME": "BrandonE-DigIt-PRD-5cd429718-3d6a116b",
"GLOBAL-ID": "EBAY-US",
"RESPONSE-DATA-FORMAT": "JSON",
"REST-PAYLOAD": "",
"itemFilter(0).name": "MinPrice",
"itemFilter(0).value": "7.00",
"itemFilter(0).paramName": "Currency",
"itemFilter(0).paramValue": "USD",
"paginationInput.pageNumber": "1",
"sortOrder": "",
"paginationInput.entriesPerPage": "50",
"categoryId": "176985"
}
return this;
}
// looks at the dom and fills the sortOrderParam
buildfindCompletedItemsUrl.prototype.getSortOrder = function() {
var $filters = $("[data-filter]");
let param = this.defaultUrlParams["sortOrder"];
let _ = this;
$.each($filters, function(i, f) {
let $filter = $(f);
let data = $filter.data();
let val = data.value;
if (val == true) {
if (_.defaultUrlParams["sortOrder"] == "") {
_.defaultUrlParams["sortOrder"] += data.filter;
} else {
_.defaultUrlParams["sortOrder"] += "," + data.filter;
}
}
})
};
// builds the full url for the ajax call
buildfindCompletedItemsUrl.prototype.build = function() {
let _url = this.url;
let keys = Object.keys(this.defaultUrlParams);
let length = keys.length;
for (let i = 0; i < length; i++) {
let key = keys[i];
let val = this.defaultUrlParams[key];
if (i == 0) {
_url += `?${key}=${val}`;
} else {
_url += `&${key}=${val}`;
}
}
return _url;
}
// get your results and return them
function GetFilteredResults(url, callback) {
// do ajax here
return callback(url)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-filter="date" data-value="false">Sort By Date</button>
<button data-filter="price" data-value="false">Sort By Price</button>

how to print my array on desktop and replace by sorted array

I write code that print names on desktop. If I click button it should replace with sorted names.
For example I have:
Johny
Amber
Michael
And after press button should be replaced by:
Amber
Johny
Michael
My code:
<div>
<ul>
<script>
var Tab = new Array('Johny', 'Amber', 'Michael')
for (x=0; x<Tab.length; x++) {
w= "<li>" + Tab[x] + "</li>"
document.write(w);
}
function myFunc(){
var str = document.getElementById(w).value;
var res = str.replace(w, Tab.sort());
document.getElementById(w).innerHTML = res;
}
</script>
</ul>
</div>
<button type="button" id="sort" onclick="myFunc()">Sort</button>
I have problem with myFunc().
How to replace/overwrite them?
If you want to write your list more than one time, then create a function for it. You will save time and code. I've called it printTab. To access the ul tag with JS, I've added an id to it: list. And now myFunc: let's just simply sort an array and print it again.
<div>
<ul id="list">
<script>
var Tab = new Array('Johny', 'Amber', 'Michael')
function printTab() {
var w = '';
for (x=0; x<Tab.length; x++) {
w += "<li>" + Tab[x] + "</li>"
}
document.getElementById("list").innerHTML = w;
}
// we must be sure that DOM is loaded if we want to manipulate on it
document.addEventListener("DOMContentLoaded", function(event) {
printTab();
});
function myFunc(){
Tab.sort();
printTab();
}
</script>
</ul>
</div>
<button type="button" id="sort" onclick="myFunc()">Sort</button>
My advice for you is to place scripts in a better place than inside some random tags, because it's making your HTML document chaotic and page load order pretty random. The best place for JS scripts is just before </body>.
You have to reference the id of the div whose inner HTML you are modifying. Here is the fiddle
<html>
<div id="stuff">
</div>
<button type="button" id="sort" onclick="myFunc()">Sort</button>
<script>
var Tab = new Array('Johny', 'Amber', 'Michael');
function formList(Tab) {
var w = "<ul>";
for (x = 0; x < Tab.length; x++)
w += "<li>" + Tab[x] + "</li>";
w += "</ul>";
return w;
}
document.getElementById("stuff").innerHTML = formList(Tab);
function myFunc() {
document.getElementById("stuff").innerHTML = formList(Tab.sort());
}
</script>
</html>

Change Div background color using HEX value stored in json file

(I updated my code to remove the br from info2)
I want to use jQuery to read a JSON file (it contains a color name and its hex value) and load the color names into a drop-down select (I got this part working). Then I want the div next to the drop-down select to change to the selected color when the user changes the value of the drop-down select. How do I change the div background color to that of the hex value for the color the user selects?
My page:
<script language="javascript" type="text/javascript">
var JSON_Response;
$(document).ready(function () {
$.getJSON('Colors.json', function (data) {
JSON_Response = data;
var mySelect = document.getElementById("selColor");
for (i = 0; i < JSON_Response.Colors.length; i++) {
var myOption = document.createElement("option");
myOption.text = JSON_Response.Colors[i].colorName;
myOption.value = i;
try {
mySelect.add(myOption, mySelect.options[null]);
}
catch (e) {
mySelect.add(myOption, null);
}
}
});
$("#selColor").change(function () {
var myIndex = $("#selColor").val();
$("#showColor").attr("src", JSON_Response.Colors[myIndex].hex);
var info = JSON_Response.Colors[myIndex].colorName + "<br />";
info += JSON_Response.Colors[myIndex].hex+ "<br />";
var info2 = JSON_Response.Colors[myIndex].hex;
$("#divDisplay").html(info).css({'background-color' : '#' + info2});
});
});
</script>
Don't append <br /> to info2, since it's supposed to just contain a color code.
var info2 = JSON_Response.Colors[myIndex].hex;
You basically have it. The error is in the background-color value you're setting for the div.
$("#divDisplay").html(info).css({'background-color' : '#' + info2});
should read
$("#divDisplay").html(info).css({'background-color' : '#' + JSON_Response.Colors[myIndex].hex});
Basic working fiddle example
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<button>Click me</button><br/>
<div id="myDiv" style="height:400px;width:400px;">
</div>
<script>
var hexChars = "ABCDEF0123456789";
function getColor() {
var colorStr = "";
for(var idx=0; idx < 6; idx++ ) {
colorStr += hexChars.charAt(Math.floor(Math.random() * hexChars.length));
}
return colorStr;
}
$('document').ready(function() {
$('button').click(function() {
var rand = getColor();
$('#myDiv').html('#' + rand).css({ 'background-color' : '#' + rand });
});
});
</script>
</body>
</html>

Categories