Determine if an element is exists - javascript

Am creating a comment system for a web app, the comments are loaded when a user clicks on the comment image, html code is dynamically generated with json to display the comments.
But when the image is clicked again,the request is made again populate the page with the same data
Heres my code
function latest_pheeds() {
var action = url+"pheeds/latest_pheeds";
$.getJSON(action,function(data) {
$.each(data,function(index,item) {
$('#pheed-stream').append
(
'<div class="pheed" id="'+item.pheed_id+'">'+
'<p>'+item.user_id+'</p>'+
'<p>'+item.pheed+'</p>'+
'<div class="pheed_meta">'+
'<span>'+item.datetime+' Ago</span>'+
'<span>'+item.comments+
'<img class="comment_trigger" src="/pheedbak/assets/img/comment.png" title="Click to comment on pheed" onclick="retrieve_comments('+item.pheed_id+')">'+
'</span>'+
'</div>'+
'</div>'
);
});
});
}
function retrieve_comments(pheed_id) {
var action = url+'comments/get_comments';
var crsf = $('input[name=ci_csrf_token]').val();
var dataString = "pheed_id="+pheed_id+"&ci_csrf_token="+crsf;
$.ajax({
url:action,
type:'POST',
cache:false,
dataType:'json',
data:dataString,
success:function(data) {
$.each(data,function(index,item) {
$("#" + pheed_id).append(
'<div class="pheed_comments">'+
'<div class="comment">'
+'<span><p>'+item.user+'</p></span>'
+item.comment+
'</div>'+
'</div>'+
'<div id="comment_box">'+
'<textarea id="comment" cols="30">'+
'</textarea><br>'+
'<input type="button" class="submit_btn" value="comment" />'+
'</div>'
);
});
}
});
}
latest_pheeds() loads the pheeds and retrieve_comments gets the comments of the pheed_id passed to it.
How do i determine if the comment area has already been populated and instead update it with new comments if available. Thanks

Check for
$("#" + pheed_id +' .pheed_comments').length
if will be 0 if the element(I guess vou mean div.pheed_comments ) doesn't exist.

Several choices:
1) If you already have all the comments from your ajax call, then just remove the previous comments you have from the DOM and insert everything you just got.
2) If you have an ajax call that can retrieve just the new comments, then you can just check the DOM to see if you already have comments in the DOM and then just request new comments after some token in time (that you would have previously saved). When you receive the new comments, you would append them to what you have.
$('#pheed-stream').children().length will tell you how many children there are in the pheed-stream hierarchy. If that's zero, you haven't done any pheeds yet.
I would suggest that it's probably easiest to just retrieve all the comments and replace everything you have with the new list of comments than to try to retrieve just the new comments. Retrieving just the new comments will require some sort of time token that you can give the server so it knows which "new comments" to give you.
$("#" + pheed_id + " .pheed_comments").length will tell you whether any comments have been retrieved yet for that pheed_id.

you are adding div with id. Just check if it exists. If yes, then update it, otherwise insert.

Related

executing JS function and define variable from html

What I have is a page which is gathering a large list of data via jQuery. I am trying to limit the amount of results shown to a variable, and change the results shown on the list to create a false-page effect. Everything works via the same JS function, and relies on 1 variable to make everything work. Simple. I've removed all of the extra code to simplify everything
function myFunction() { var page = 1; console.log(page); }
I am looking for a way to call on this function, but change the variable 'page' from within html. Something along the lines of:
2
I have been looking on google (and still am) I just can't seem to find what I am looking for. I'm trying to avoid multiple pages/refreshing as this element is going to be used for a larger project on the same page.
UPDATE: I managed to pass the intended values through to a JS function like so...
function myFunction(page) { console.log(page); }
...and...
<input type='button' onclick='myFunction(value)' value='input page number'>
This seems the simplest way of doing what I need, what do you think?
Thanks for your help btw guys.
To do this you will need to move the page variable to be a parameter of myFunction
function myFunction(page) { console.log(page); }
Then you can just pass in whatever page number you would like
2
Sure, you can add the data-url attribute to your markup and select on the .link class to fetch the data-url attribute for each element thats part of that class.
I'm trying to avoid multiple pages/refreshing as this element is going
to be used for a larger project on the same page.
Sounds like you also want an AJAX solution.
$(document).ready( function()
{
//Add this on your call.html page
$(".link").click(function()
{
//location of test JSON file
var root = 'https://jsonplaceholder.typicode.com';
//your custom attribute acting as your 'variable'
var page = $(this).attr('data-url');
console.log("page = " + page);
//remove any previous html from the modal
$(".modal-content").empty();
//send a request to the server to retrieve your pages
$.ajax(
{
method: "GET",
//this should be updated with location of file
url: root + '/posts/' + page,
//if server request to get page was successful
success: function(result)
{
console.log(result);
var res = result;
var content = "<div class='panel-default'><div class='panel-heading'><h3 class='panel-title'>" + res.title + "</h3></div><i><div class='panel-body'>''" + res.body + "''</i></div><p><u> Master Yoda, (2017)</u></p><p class='page'> Page: " + page + "</p></div>";
$(".modal-content").html(content);
},
//otherwise do this
error: function(result)
{
$(".modal-content").html("<div class='error'><span><b> Failed to retrieve data </b></span><p> try again later </p></div>");
}
});
});
});
.error
{
border: 2px dotted red;
margin: 5px;
}
a
{
font-size: 20px;
}
.page
{
text-align: left;
padding: 0 15px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/js/bootstrap.min.js"></script>
<a class="link" data-url="1" data-toggle="modal" data-target="#Modal" href="test.html">Show Page 1</a>
<br />
<a class="link" data-url="2" data-toggle="modal" data-target="#Modal" href="">Show Page 2</a>
<div id="Modal" class="modal fade text-center">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
</div>
I seem to have figured out how to do this. I wanted to stray from using lots of libraries in the project and just wanted to keep things simple, using the above answers for guidance (and a little more digging), basically my end goal was to use jQuery to obtain a long list of data, and format this data into a multiple page list (for which I used a table for formatting purposes). Let's say it's a list of names. The JSON results output as:
[{"first_name":"Bob"},{"last_name":"Jones"}] // (key, value)
But when I passed this through to the HTML Table it was just displaying 1000s of results in a single list, and formatting the list was a pain. This was my solution:
<script>
var pageNum = ""; // define Page Number variable for later.
var resLimit = 35; // variable to specify the number of results per page
function updateList () {
$.getJSON(" Location of JSON results ", function(data) {
var pageCount = Math.round(data.length/resLimit); // calculate number of pages
var auto_id = ((pageNum-1)*resLimit) // use variables to give each result an id
var newListData = ""; // define this for use later
then define and pass "new list data" to HTML Table:
var newListData = "";
$.each(data.slice(auto_id, (pageNum*resLimit)), function(key, value) {
auto_id++;
newListData += '<tr>';
newListData += '<td class="id">' + audo_id + '</td>';
newListData += '<td class="id">' + value.first_name + '</td>';
newListData += '<td class="id">' + value.last_name + '</td>';
newListData += '</tr>';
});
$('# ID of table, data will replace existing rows ').html(newListData);
At this point if you set the value of pageNum to 1 you should see the first 35 results on the list, all with auto-incremented ID numbers. If you change it to 2 and refresh the page you should see the next 35, with the ID numbers following on from the first page.
Next I needed to create a button for each of the pages:
$('# ID of table, data will replace existing rows ').html(newListData);
function createButtons() {
var buttonArray = "";
for(i=0, x=pageCount; i<x; i++) {
buttonArray += '<input type="button" onclick="changePage('
+ (i + 1) + ')" value="' + (i + 1) + '">';
}
$('# ID of Span tags for button container ').html(buttonArray); }
createButtons();
}); }
</script>
Then create changePage() and a function to refresh the data in the list automatically without messing things up
<script>
var pageNum = "";
function changePage(page) {
if (pageNum < 1) { pageNum = 1; } // set pageNum when the page loads
if (page > 0) { pageNum = page; } // overwrite pageNum when 'page' variable is defined
updateList(); }
changePage(); // initialise to prevent delayed display on page load
// refresh function:
function refreshData() {
changePage(0); // define 'page' as 0 so that pageNum is not overwritten
window.setTimeout(refreshData, 5000); } // loop this function every 5 seconds to
refreshData(); //-- keep this list populated with current data.
And that should just about do it! At least it's working for me but I might have missed something (hopefully not lol). Hope this helps someone theres quite a few things involved in this that could be extrapolated and used elsewhere :)
thanks for help everyone.

Uncaught ReferenceError: is not defined onclick when using character strings

I am trying to pass a variable to the onClick function using a previously stored value. I have a database setup that searches for store locations when provided with a ZIP code. For example, the following link is generated using an ajax call after a user searches for a Zip Code. The returned value "WAFHOH3" is the ID that is associated with that particular store:
Generated Link:
<input type="button" onclick="myfunction(WAFHOH1);" value="This Is My Store" data-store-code="WAFHOH3">
Based on this code:
<div class="col-sm-3"><input type="button" onclick="myfunction(' + item.store_code + ');" value="This Is My Store" data-store-code="' + item.store_code + '"></div>
My problem is that if anything other than a number is returned I get a "Uncaught ReferenceError: WAFHOH3 is not defined" console error. When a number is passed like the example below, everything works fine and I get no errors and the application continues to work as expected.
For example (This Works):
Ive tried manually changing the character string to numbers only to isolate any database related issues. My only guess is that there is something in my code that is maybe attempting to verify the input as number.
The full code is below for the ajax call.
Full Code:
function myFunction() {
var searchValue = $('#foobar').val();
if (searchValue.length > 3) {
var acs_action = 'searchCction';
$.ajax({
async: false,
url: mysearchurl.url+'?action='+acs_action+'&term=' + searchValue,
type: 'POST',
data: {
name: searchValue
},
success: function (results) {
var data = $.parseJSON(results);
$('#resContainer').hide();
var html = '';
if (data.length > 0) {
html += '<br/><br/><ul>';
for (var i = 0; i < data.length; i++) {
var item = data[i];
html += '<li>';
html += '<div class="row myclass">';
html += '<div class="col-sm-9">';
html += ' <h3>' + item.label + '</h3>' ;
html += ' <span>' + item.desc + '</span>';
html += '</div>'
html += ' <div class="col-sm-3"><input type="button" onclick="dofunction(' + item.store_code + ');" value="This Is My Store" data-store-code="' + item.store_code + '"></div>';
html += '</div>';
html += '</li>';
}
html += '</ul><br/><br/><p>This is an example message please email us at admin#admin.com for assistance.';
}
else {
html += '<br/><br/><p>This is an example message, email us at admin#admin.com for assistance.';
}
$('#foo').html(html);
$('#foo').show();
$('.foobar').hide();
}
});
} else {
$('#foo').hide();
}
}
You need to wrap the input item.store_code with quotation marks; otherwise, it tries to treat it as a variable, not a string:
html += '<div class="col-sm-3"><input type="button" onclick="noActivationCodeRegistration(\'' + item.store_code + '\');" value="This Is My Store" data-store-code="' + item.store_code + '"></div>';
Ideally, you would attach a click handler after giving the buttons a class (such as register):
html += '<div class="col-sm-3"><input type="button" class="register" value="This Is My Store" data-store-code="' + item.store_code + '"></div>';
// Later
$('.register').on('click', function() {
var storeCode = $(this).data('storeCode');
noActivationCodeRegistration(storeCode);
});
I may be late, and maybe its an absolute mistake of me, but, i have to add my answer here because i just solved exactly the same situation in about three minutes ago .
I just solved this using the most simple sollution, and the error "Uncaught ReferenceError" from the console is solved, also i have my alert(); passing the variable as i needed.
I also need to include that i did not aproove the sollution gave, about "not using" the alert function, once i searched for the sollution, not for another method for that .
So, as i am using php, and the document is html, i thinked about the apostrophe charactere to the variable, after i had been spectating the element using chrome, first moving the function alert to the parent and child elements, that not solved .
After, also in the specting element, inside chrome F12 i tryed changing the function, including '' (that i passed in php code) into variable inside the alert function as: onclick="alert(variable);" to onclick="alert('variable');" and my alert had worked .
Ok. So, i try everything to insert '' 2 single quotes '' to my variable in php, that seems impossible, even if i change all my code to " and use ' or the oposite .
Then, i decided to try the most obvious and old school method, that is about charactere representation, and i cfound that ' (single quote) is represented by ' in php. Everything inside ->> ' <<-
My php code is like this : onclick="alert(&#039'.$variable.'&#039);"
It will work! (with no Vue), ok ? :)

Set and get a HTML created in javascript to session local storage

I need that the below code persist to exist in page reload, Ok.
<br/>
<div style="font-size: 8pt;float: left;width:100%;margin-left: 15px;margin-top:5px;">
some text here
</div>
<div style="width: 100%; height: 40px;">
<div class="flechaDestinatario"/>
<div class="textoDestinatario">
more text here
</div>
</div>
I need to add dynamically in javascript some more elements, but you can consider it as example.
I put the elements of code above in a parent div, the div parent id is 'chatUsuario' and the javascript var name is 'mensagem', anyway,
var mensagem = document.getElementById('chatUsuario');
if (mensagem != null) {
$(mensagem)
.append(
'<br/> <div style="font-size: 8pt;float: left;width:100%;margin- left: 15px;margin-top:5px;">'
+ args.dataHora
+ '</div>'
+ '<div style="width: 100%; height: 40px;">'
+ '<div class="flechaDestinatario"/>'
+ '<div class="textoDestinatario">'
+ args.mensagemRetorno
+ '</div>'
+ '</div>');
}
I try many things, but nothing with success, for example:
localStorage.setItem('mensagensBackup',JSON.stringify(mensagem));
$(window).load(function() {
var mensagensBackup = localStorage.getItem('mensagensBackup');
if(mensagensBackup!=null)
{
var retrievedObject = JSON.parse(mensagensBackup);
document.getElementById('chatUsuarioContainer').innerHTML=retrievedObject;
}
});
I try too jStorage.js, without success again.
Both cases I have the same error: "converting circular structure to json"
I really try, but I can't solve this error
Any another solution? have a workaround solution? something that I can do?
Thanks so much ;)
PS: I using JSF 2.2 and Prime 5
You can't stringify a DOM element object directly because it contains a circular reference to itself (as the error message says). On the other hand you don't even want to do that because you're interested only in its HTML content anyway. So change the code to
localStorage.setItem( 'mensagensBackup', mensagem.innerHTML );
and later remove the JSON.parse() line which is unnecessary now.
(As a side note, most of the time it's more reasonable to save some sort of abstraction of the data instead of the entire HTML, but that's another discussion.)
you can store html sub tree in localStorage and restore in after reload
localStorage.setItem('mensagensBackup',mensagem.innerHTML));
$(function() {
var mensagensBackup = localStorage.getItem('mensagensBackup');
if(mensagensBackup)
document.getElementById('chatUsuarioContainer').innerHTML = mensagensBackup;
}
});

Retrieve specific data stored with JSON

I've used the code posted in THIS STACKOVERFLOW POST to build a prototype of a webbapp, but I can't make the second page show me the data with the format I want.
The code shows me the second page with all the data in a grid format, but I want to know how to make specific data with different formats (bold, italic, color).
For example, one string that I use is a "image.jpg" text to load an image of the user.
I've modified the first part of the code to:
$.each(info, function (i, valor) {
li += '<li><img src="img/'+ valor.foto +'"><h2><i>' + valor.cientifico + '</i></h2><p><b>Familia:</b> <i>'+ valor.familia +'</i> | <b>Subfamilia:</b> <i>'+ valor.subfamilia +'</i></p></li>';
});
to add specific values and apply different format (familia, subfamilia) and to insert the picture with the "foto" value.
Then the code continues:
$("#lista").append(li).promise().done(function () {
$(this).on("click", ".info-go", function (e) {
e.preventDefault();
$("#resultado").data("info", info[this.id]);
$.mobile.changePage("#resultado");
});
$(this).listview("refresh");
});
});
$(document).on("pagebeforeshow", "#resultado", function () {
var info = $(this).data("info");
var info_view = "";
for (var key in info) {
info_view += '<div class="ui-grid-a"><div class="ui-block-a"><div class="ui-bar field" style="font-weight : bold; text-align: left;">' + key + '</div></div><div class="ui-block-b"><div class="ui-bar value" style="width : 75%">' + info[key] + '</div></div></div>';
}
$(this).find("[data-role=content]").html(info_view);
});
I know that the for (var key in info) is not what I'm looking for, but I don't know what code I have to use because I'm too new to unsderstand how to do it. How can I accomplish this?
The code next to info_view is HTML, right, but if I replace + key + with + familia + for example this doesnt works like before.
My question is how can I make to retrieve an specific data (for example the foto value) of the selected item listed in the first page? I want to be able to select wich items use. For example, I wanna make the id value invisible for the user, make the id value invisible, the name value in bold, and so on
Hope I was enough clear, sorry for my limited english and coding knowledge
Finnaly I've solved my own question.
For reference, what I do was deleted the
for (var key in info) {
and inside the info_view += part i've used info['value'] for each item I want to manipulate.
Hope this helps someone else.

how to give id dynamically to an element in phonegap?

Hi i am doing an application in phonegap,in that application i need to show list of the users in the listview contains profile pic,name,number and online status .
for (var i = 0; i < roster_items.length; i++) {
var jid_contact=roster_items[i].getAttribute('jid');
var name_contact=roster_items[i].getAttribute('name');
/// Add all the contacts to Array
$('#contacts-listview').append(
'<a href="#" onclick="user_contactsClicked('+ i + ');">' +
'</br>'+
'<div id="contact_img">'+
'<img id="splash" src="images/contact_default_pic.png" />'+
'<ul id="menu">'+'<li id="contact">'+name_contact+'</li>'+
'<li id="status">'+jid_contact+'</li>'+'</ul>'+
'<div class="pull-right"><div><img id=i class="status_img" src="images/user_online.png" /></div>'+
'<div style="margin-bottom: 10px;"><ol id="date">'+
'<li>date</li>'+
'<li>time</li>'+
'</ol></div></div>'+
'</div>'+
'</br>'+
'</a>'
);
}
and i will call a function for changing the online status for a particular user and changes the image
changeOnlineStatus_contact : function(elementPos) {
alert(elementPos);
if(elementPos>=0) {
//Get current table
document.getElementById(i).src = "images/user_offline.png";
}
}
for this i want to give if for the img element dynamically. Please suggest me.
Thanks in advance..
The reason the id isn't getting set on the image is because you've got:
"…<img id=i class=…" which means that every image has the id of "i"
If you changed this to:
"…<img id=\""+i+"\" class=…" then it would use the value of i as the id attribute
If you have more complex bindings to the UI, I'd recommend looking at something like http://knockoutjs.com/ - this way you would update the underlying model, and the html would automatically be updated to represent it.

Categories