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
Related
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.
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>
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>
So, I want to to modify the Array so that it displays its content in table, row by row, a single time. With the code below it displays the code progressively each element appearing more than once.
How to solve this? thx.
$(function() {
Array.prototype.ToTable=function(){
tabelul="<center><table border><tr>";
for(a=0; a<this.length;a++){
this[a]=tabelul+="<td> <div class='Expresion'>" + this[a] + "</div></td></tr>"
}
}
vaz=['one', 'two', 'three','four'];
vaz.ToTable();
$('#show').html(vaz)
})
<div id="show"></div>
I believe what you meant to do was something along the lines of this:
for(a=0; a<this.length;a++){
tabelul+="<tr><td><div class='Expresion'>" + this[a] + "</div></td></tr>";
}
You should build the tabelul variable and then return it.
Here is an example of doing that
Here is a row demo: http://jsfiddle.net/2zchT/2/
html:
<div id="show"></div>
js:
$(function() {
Array.prototype.ToTable=function(){
var tabelul = "<center><table border>";
for(var a=0; a<this.length;a++){
tabelul += "<tr><td><div class='Expresion'>" + this[a] + "</div></td></tr>"
}
tabelul += "</table></center>";
return tabelul;
};
vaz=['one', 'two', 'three','four'];
$('#show').html(vaz.ToTable())
})
Edit
You should seed that data in before you build the table.
var Links= new Array();
Links[0]='<img src="http://photo1.com/">';
Links[1]='<img src="http://photo2.com/">';
Links[2]='<img src="http://photo3.com/">';
Links[3]='<img src="http://photo4.com/">';
Links[4]='<img src="http://photo5.com/">';
var vaz=['one', 'two', 'three','four'];
for( var i = 0; i < vaz.length; i++ )
{
vaz[i] = Links[i] + vaz[i];
}
Here is a demo: http://jsfiddle.net/2zchT/4/
how do you change a inner id with js and keep it the same id num (e.g hey1, bob2)
my js code
var obj = document.getElementById("chat").cloneNode(true);
var obj1 = document.getElementById("ch");
var obj2 = document.getElementById("chatbox");
var p = $(".chat");
var offset = p.offset();
num = num + 1;
if (num <=15) {
obj.id = obj.id + num; <--- **changing the id (this one works fine but the other two dont**
obj1.id = obj1.id + num; <--- changing the id
obj2.id = obj2.id + num; <--- changing the id
document.body.appendChild(obj);
document.body.appendChild(obj1);
document.body.appendChild(obj2);
var left = offset.left + 275;
document.getElementById("chat").style.left = left + "px";
tell me if i am doing it wrong but this was the easiest way i thought off
(ps i am a beginner at javascript)
thanks to all that try to help...
Edit
ok i clone this
<div class="chat" id="chat">
<div id="ch" class="ch">
<h2>Chat</h2></div>
<div class="chatbox" id="chatbox">
<div class="messages"></div>
<textarea id="message" class="chatinp"
rows="3" cols="27"></textarea>
<button class="send">Send</button></div>
</div>
and everytime it clones it changes the id of chat,ch and chatbox but keeping the original the same
like so...
clone1
<div class="chat" id="chat1">
<div id="ch1" class="ch">
<h2>Chat</h2></div>
<div class="chatbox" id="chatbox1">
<div class="messages"></div>
<textarea id="message" class="chatinp"
rows="3" cols="27"></textarea>
<button class="send">Send</button></div>
</div>
Clone2
<div class="chat" id="chat2">
<div id="ch2" class="ch">
<h2>Chat</h2></div>
<div class="chatbox" id="chatbox2">
<div class="messages"></div>
<textarea id="message" class="chatinp"
rows="3" cols="27"></textarea>
<button class="send">Send</button></div>
</div>
Not sure, but if I'm right, you're trying to create a new 'chatnode'. You'll have to traverse the childNodes array of the node you cloned to change id's. Try something like:
function cloneChat(){
var obj = document.getElementById("chat").cloneNode(true),
children = obj.childNodes
;
num += 1;
obj.id = obj.id+num;
if (num<16){
changeId(children,num);
}
//now appending obj to the document.body should be sufficient
document.body.appendChild(obj);
//change id recursively
function changeId(nodes, n){
for (var i=0;i<nodes.length;i=i+1){
if (nodes[i].childNodes){
changeId(nodes[i].childNodes,n);
}
if(nodes[i].id && /^ch$|^chatbox$/i.test(nodes[i].id)) {
nodes[i].id += String(n);
}
}
}
}
See this jsfiddle for a working example
Furthermore, this code won't work:
var p = $(".chat");
var offset = p.offset();
Because $(".chat") returns a list of nodes, where every node has it's own offset.
You seem to be using jQuery, so I suggest adding a 'jQuery' tag to your question. Maybe some jQuery whizzkid has a solution to offer.
In jQuery try to use
element.attr("id","newId");
See: http://api.jquery.com/attr/
How about this function?
function appendMe() {
var elementsToClone = ["chat"]; //Parent Elements to clone. This is the class name as well as the id
var childrenToHandle = new Array();
childrenToHandle["chat"] = ["ch"]; //Child elements mapping to keep sync. This is the class name as well as the id. Here we say that for the parent element chat, the inner elements to keep in sync is ch
var itemCount = 0;
for(i = 0; i < elementsToClone.length; i++) {
var refObj = document.getElementById(elementsToClone[i]);
if(refObj) {
$("." + elementsToClone[i]).each(
function() {
if(this.id.match(/\d+$/g)) {
itemCount = this.id.match(/\d+$/g);
}
}
);
var newObj = refObj.cloneNode(true);
newObj.id = elementsToClone[i] + ++itemCount;
var childrenArray = childrenToHandle[elementsToClone[i]];
if(childrenArray) {
$(childrenArray).each(
function() {
$(newObj).find("." + this).attr("id", this + itemCount);
}
);
}
document.body.appendChild(newObj);
}
}
}
Since you're already using jQuery in your code, how about:
var $obj = $("#chat").clone(),
$obj1 = obj.find("#ch"),
$obj2 = obj.find("#chatbox");
var p = $(".chat"),
offset = p.offset();
num = num + 1;
if (num <= 15) {
$obj.attr('id', $obj.attr('id') + num);
$obj1.attr('id', $obj1.attr('id') + num);
$obj2.attr('id', $obj2.attr('id') + num);
$('body').append(obj);
var newLeft = offset.left + 275;
$('#chat').css({
left: newLeft
});
}