Updating <li> text using JSON data - javascript

I trying to update dynamically added li text (html code) with the JSON data as below script, but the update method are not working, could you help me to check?
City
<input type="text" id="cinput">
<br>
<input type="button" id="cadd" value="Add">
<input type="button" id="cup" value="Update">
<div class="clista">
<ul class="lista inset" id="citem">
<li data-val="Campinas">Campinas [T:00ºC H:00%] <span style="float:right;"><b>[X]</b></span>
</li>
<li data-val="Sao Paulo">Sao Paulo [T:00ºC H:00%] <span style="float:right;"><b>[X]</b></span>
</li>
</ul>
</div>
Javascript
$("#cadd").on("click", function () {
var cinput = document.getElementById("cinput").value;
var msg = "'Remover?'";
$.getJSON("http://api.openweathermap.org/data/2.5/weather?q=" + cinput + "&units=metric", function (data) {
var cdados = ('T:' + data.main.temp + 'ºC H:' + data.main.humidity + '%');
$('#citem').append('<li data-val="' + cinput + '">' + cinput + " [" + cdados + ']<a href="#" onclick="if(confirm(' + msg + ')){parentNode.parentNode.removeChild(parentNode)}"> <span style="float:right;"><b>[X]</b></span></li>');
document.getElementById("cinput").value = "";
});
});
$("#cup").on("click", function () {
var cidade = '';
var oldText = '';
var novotxt = '';
var msg = "'Remover?'";
var Link = (' <span style="float:right;"><b>[X]</b></span>');
$('.clista li').each(function () {
var $this = $(this);
cidade = $(this).data('val');
oldText = $(this).html();
$.getJSON("http://api.openweathermap.org/data/2.5/weather?q=" + cidade + "&units=metric", function (data) {
var cdados = ('T:' + data.main.temp + 'ºC H:' + data.main.humidity + '%');
novotxt = cidade + " [" + cdados + "] ";
alert(novotxt);
$this.html(function (index, html) {
return html.replace(oldText, novotxt + Link);
});
});
});
});
jsFiddle here: http://jsfiddle.net/fabiobraglin/rcheaowx/21/

You're hitting an asynchronous issue here. You have $.each and within that you're setting oldText and trying to use it's value within the callback of getJSON. However, the entirety of the $.each loop will run before any of the getJSON callbacks are run, so oldText will end up being set to the final element in the collection for ALL of the callbacks, so it will only ever be correct for the final element.
There's two things to note here: the html parameter of this callback:
$this.html(function (index, html) {
return html.replace(oldText, novotxt + Link);
});
should be functionally equivalent to what you're trying to use oldText for. However, the element's contents are also cleared out before this callback is run, and whatever you return from it will be the entire contents of the element, so there's no need to try to replace the oldText in this way. Just return your new content:
$this.html(function (index, html) {
return novotxt + Link;
});
If you do find youself in a situation where the variables from the loop need to be available within the callback, you can create a closure as follows:
$('.clista li').each(function () {
var $this = $(this);
cidade = $(this).data('val');
oldText = $(this).html();
(function getData(_oldText, _cidade) {
$.getJSON("http://api.openweathermap.org/data/2.5/weather?q=" + _cidade + "&units=metric", function(data) {
var cdados = ('T:' + data.main.temp + 'ºC H:' + data.main.humidity + '%');
novotxt = _cidade + " [" + cdados + "] ";
alert(novotxt);
$this.html(function(index, html) {
return html.replace(_oldText, novotxt + Link);
});
});
})(oldText, cidade);
});

Related

Textarea not generating from jQuery

I'm trying to make a website using jquery-1.11.1 where I want a <textarea> to be spawned whenever I click on the link which only shows on mouseenter on a div. But I'm getting an error in my console,
Uncaught ReferenceError: inputdivEditor is not defined (Please ignore JSFiddle errors)
I've absolutely no idea why I'm getting this. Here are my codes,
$(document).ready(function () {
$("[id^=divEditor-]").each(function () {
var content = $(this).html();
var targetID = $(this).attr('id');
var txtID = 'input' + targetID;
$('<textarea id="input' + targetID + '" name="' + txtID + '" >' + content + '</textarea>').insertBefore(this).css('display', 'none');
var button = "<a onclick='activateDivEditor(this, " + txtID + ")' class='custom-edit-button editDiv' id='active" + targetID + "'>Embed Code</a>";
$(this).on('mouseenter', function () {
$(this).prepend($(button));
$(this).css('position', 'relative');
});
$(this).on('mouseleave', function () {
$('.editDiv').remove();
});
});
});
function activateDivEditor(btn, txtId) {
var targetID = $(btn).parent().get(0).id;
var update = "<a onclick='deactivateDivEditor(this, " + txtId + ")' class='custom-edit-button updatediv' id='deactive" + targetID + "'>Update</a>";
var cancel = "<a onclick='cancelactivateDivEditor(this)' class='custom-edit-button cancel' id='cancelactive" + targetID + "'>Cancel</a>";
var targetClass = $('#' + targetID).attr('class');
var targetWidth = $('#' + targetID).width();
$('#' + targetID).css('display', 'none');
$('#input' + targetID).css('display', 'block').css('width', targetWidth - 2).css('height', '125px');
$('#input' + targetID).parent().css('position', 'relative');
$(update).prependTo($('#input' + targetID).parent());
$(cancel).prependTo($('#input' + targetID).parent());
}
JSFiddle Demo
How can I generate a textarea whenever I click on the button link? Need this help badly. Thanks.

what is the correct syntax form for this to function -- Javascript

In the following lines of code, I try to add a function inside html tag in javascript:
nuevo = "<p class='item'>" + res.tarea + "<button onclick = '" + return EliminarTareas(database) + (" + res.tarea +");'>" + "Eliminar" + "</button></p>";
$('#listatareas').append(nuevo);
function EliminarTareas(id, base) {
base.transaction(function(tx) {
tx.executeSql("DELETE tarea FROM Tareas WHERE tarea=?", [id], function () {
});
});
}
The main problem is this part +return EliminarTareas(" + database + ", " + res.tarea +");'>". It discards the second parameter since you closed the paranthesis ), and it also has quote problems.
It should be like this +" return EliminarTareas(" + database + ", " + res.tarea + ");'>"
However, I believe addressing this task with .data would be effective, and it may provide a better structure. Below is my version with some codes from yours (DEMO: https://jsfiddle.net/9q4hLs3a/):
var nuevo = $("<p class='item'><button data-var1='" + database + "' data-var2='" + res.tarea + "'>Eliminar</button></p>");
$('#listatareas').append(nuevo);
$(document).ready(function(){
$(document).on('click', '#listatareas button', function(){
var var1 = $(this).data('var1');
var var2 = $(this).data('var2');
EliminarTareas(var1 , var2 )
});
function EliminarTareas(id, base){
base.transaction(function(tx){
tx.executeSql("DELETE tarea FROM Tareas WHERE tarea=?", [id], function (){
});
}
I think this is what you wanted
"<p class='item'>"+ res.tarea +"<button onclick = 'EliminarTareas("+database+","+res.tarea +")'>Eliminar</button></p>";

Hiding <p> field in javascript

Here's my code for gathering titles/posts from reddit's api:
$.getJSON("http://www.reddit.com/search.json?q=" + query + "&sort=" + val + "&t=" + time, function (data) {
var i = 0
$.each(data.data.children, function (i, item) {
var title = item.data.title
var url = item.data.url
var id = item.data.id
var subid = item.data.subreddit_id
var selftext = item.data.selftext
var selftextpost = '<p id="post' + i + '">' + selftext + '</p><br>'
var post = '<div>' + '' + title + '' + '</div>'
results.append(post)
results.append(selftextpost)
i++
});
});
Basically every post (selftext) is assigned a different paragraph id (post0, post1, post2, etc) for every result that's pulled. I'm also going to create a "hide" button that follows the same id scheme based on my i variable (submit0, submit1, submit2, etc). I want to write a function so that based on which button they click, it will hide the corresponding paragraph. I've tried doing an if statement that's like if("#hide" + i) is clicked, then hide the corresponding paragraph, but obviously that + i doesn't work. How else can I tackle this?
Could you try something like the below?
showhide = $("<a class='hider'>Show/Hide</a>");
results.append(showhide);
$(showhide).click(function() {
$(this).next().toggle();
}
Alternatively:
$.each(data.data.children, function (i, item) {
var title = item.data.title
var url = item.data.url
var id = item.data.id
var subid = item.data.subreddit_id
var selftext = item.data.selftext
var selftextpost = '<p id="post' + i + '">' + selftext + '</p><br>'
var showhide = $("<a class='hider" + i + "'>Show/Hide</a>");
var post = '<div>' + '' + title + '' + '</div>'
results.append(post)
results.append(selftextpost)
results.append(showhide);
$(showhide).click(function() {
$(this).next().toggle();
});
i++
});

EDITED How to get the json value for localStorage in a loop

after Oyeme's advise, i have changed my code, but still cannot work. it can alert "testing" but cannot alert DBuser_name .
By the following coding, i can create a content like the image below. My problem is that, if the user click one of the people in the list, i would like to extract the student.data.user_name into localStorage. however, in my coding below, seems that i did wrong?
function getStudentList() {
$.getJSON('http://mydomain.com/getStudents.php?jsoncallback=?', function(data) {
$('#studentList li').remove();
$('#load').hide();
//students = data.user_name;
$.each(data, function(index, student) {
//$('#studentList').append('<li><a href="tutor_student_detail.html?user_name=' + student.data.user_name + '">' +
$('#studentList').append('<li><a href="tutor_student_detail.html">' +
'<h4>' + student.data.user_name + '</h4>' +
'<p>' + student.data.role + '</p>' +
'</a></li>');
$("li a").click(function() {
window.localStorage["view"] = $(this).data('user_name');
});
});
$('#studentList').listview('refresh');
});
}
Below are the coding of tutor_student_detail.html (js part)
function start(){
var localUsername=window.localStorage.getItem("view");
$.getJSON('http://mydomain.com/getStudent.php?user_name='+localUsername+'&jsoncallback=?', displayStudent);
alert("testing");
}
function displayStudent(data) {
var DBuser_name=data[0].data.user_name;
alert(DBuser_name);
var employee = data.item;
$('#username').text(student.data.user_name);
$('#pw').text(student.data.password);
$('#id').text(student.data.id);
$('#actionList').listview('refresh');
}
the output of json string is something like
?([{"data":{"id":"4","user_name":"studentB","book":"4567","role":"Student"}}]);
$('#studentList').append('<li><a href="tutor_student_detail.html"
data-name="'+student.data.user_name+'">' +
'<h4>' + student.data.user_name + '</h4>' +
'<p>' + student.data.role + '</p>' +
'</a></li>');
$("li a").click(function() {
window.localStorage["view"] = $(this).data('name');
});

retrieving the twitter search feeds dynamically using ajax

Long back I used JSON and was successful to get the hash tag feeds from twitter and facebook. But presently I am just able to get the feeds but its not being updated constantly that means it not been update dynamically. I guess I need to ajaxify it, but I am not able to do that since I am not aware of ajax. Here is the code which I have used to get the twitter search feeds.
$(document).ready(function()
{
$("#Enter").click(function(event){
var searchTerm = $("#search").val() ;
var baseUrl = "http://search.twitter.com/search.json?q=%23";
$.getJSON(baseUrl + searchTerm + "&rpp=1500&callback=?", function(data)
{
$("#tweets").empty();
if(data.results.length < 1)
$('#tweets').html("No results JOINEVENTUS");
$.each(data.results, function()
{
$('<div align="justify"></div>')
.hide()
.append('<hr> <img src="' + this.profile_image_url + '" width="40px" /> ')
.append('<span><a href="http://www.twitter.com/'
+ this.from_user + '">' + this.from_user
+ '</a> ' + makeLink(this.text) + '</span>')
.appendTo('#tweets')
.fadeIn(800);
});
});
});
});
function makeLink(text)
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
return text.replace(exp,"<a href='$1'>$1</a>");
}
The code below should help you. What I've done is moved the code which fetches the tweets into a function. This function is then called every X seconds to update the box. When the user enters a new search term and clicks "Enter", it will reset the timer.
var fetchSeconds = 30; //Number of seconds between each update
var timeout; //The variable which holds the timeout
$(document).ready(function() {
$("#Enter").click(function(event){
//Clear old timeout
clearTimeout(timeout);
//Fetch initial tweets
fetchTweets();
});
});
function fetchTweets() {
//Setup to fetch every X seconds
timeout = setTimeout('fetchTweets()',(fetchSeconds * 1000));
var searchTerm = $("#search").val();
var baseUrl = "http://search.twitter.com/search.json?q=%23";
$.getJSON(baseUrl + searchTerm + "&rpp=1500&callback=?", function(data) {
$("#tweets").empty();
if (data.results.length < 1) {
$('#tweets').html("No results JOINEVENTUS");
}
$.each(data.results, function() {
$('<div align="justify"></div>').hide()
.append('<hr> <img src="' + this.profile_image_url + '" width="40px" /> ')
.append('<span>' + this.from_user + ' ' + makeLink(this.text) + '</span>')
.appendTo('#tweets')
.fadeIn(800);
});
});
}
function makeLink(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
return text.replace(exp,"<a href='$1'>$1</a>");
}
Hope this helps

Categories