As you can see, I have defined a global variable called filas, which in the function get_filas (full_text), I assign it the value full_text.split (": & ^").Then I must use that assigned value in the following function () but I get the following console output: Unncaught TypeError: Cannot read property 'split' of undefined.
How then is it possible to define the rows variable and assign it a data to then use them in another function?
var filas;
var cantidad_de_eventos_vistos;
window.onload = function(){
get_data();
var ul = document.getElementById("dynamic-list");
ul.onclick = function(event) {
var target = getEventTarget(event);
alert(target.innerHTML);
};
cantidad_de_eventos_vistos=2;
}
function get_data(){
console.log("algo");
var request = new XMLHttpRequest();
var url = 'http://192.168.0.248:10000'
request.open("POST", url, true);
var header="#:::|$&!";
var mensaje = "get_data"
request.send(header+mensaje);
request.onreadystatechange = function() { // Call a function when the state changes.
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
console.log(request.responseText);
get_filas(request.responseText);
}
}
}
function get_filas(texto_completo){
filas=texto_completo.split(":&^");
if (2 < filas.length){
for (var i = 1; i < 2+1; i++) {
var ul = document.getElementById("dynamic-list");
var candidate = document.getElementById("candidate");
var li = document.createElement("li");
li.setAttribute('id',filas[i].split(";¬")[0]);
li.appendChild(document.createTextNode(filas[i].split(";¬")[0]));
ul.appendChild(li);
cantidad_de_eventos_vistos=cantidad_de_eventos_vistos+2;
}
btn_siguiente.style.visibility="visible"
}
else{
for (var i = 1; i < filas.length; i++) {
var ul = document.getElementById("dynamic-list");
var candidate = document.getElementById("candidate");
var li = document.createElement("li");
li.setAttribute('id',filas[i].split(";¬")[0]);
li.appendChild(document.createTextNode(filas[i].split(";¬")[0]));
ul.appendChild(li);
}
}
}
function siguiente(){
var ul = document.getElementById("dynamic-list");
ul.parentNode.removeChild(ul);
for (var i = 1+cantidad_de_eventos_vistos; i < cantidad_de_eventos_vistos+2+1; i++) {
var candidate = document.getElementById("candidate");
var li = document.createElement("li");
li.setAttribute('id',filas[i].split(";¬")[0]);
li.appendChild(document.createTextNode(filas[i].split(";¬")[0]));
ul.appendChild(li);
if(cantidad_de_eventos_vistos!=filas.length){
cantidad_de_eventos_vistos=cantidad_de_eventos_vistos+2;
btn_siguiente.style.visibility="hide";
}
}
}
Related
So I'm trying to get a list of JSON objects and then loop through its elements via fori loop, creating <li> and <a> elements.
Everything works smoothly except when I try to add an onclick function to the in each iteration. I'm trying to pass the json object to the onclick function, but all tags have are showing the last json object.
What I need is for every <a> to show its corresponding json object when clicked.
Please see the code:
var url = "https://restcountries.eu/rest/v2/all"
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var countries = JSON.parse(xhttp.responseText)
var ul = document.getElementById('countries')
for (var i = 0; i < countries.length; i++) { //start iteration
var li = document.createElement("LI")
var img = document.createElement("IMG")
var a = document.createElement("A")
var textNode = document.createTextNode(countries[i].name)
img.setAttribute("src", countries[i].flag)
ul.appendChild(li)
li.appendChild(a)
a.appendChild(img)
a.appendChild(textNode);
a.setAttribute("title", countries[i].name)
var country = countries[i]
a.onclick = function(){ CountryClicked(country)} //pass the current JSON to the onclick function of the current <a> Node, this isn't working correctly.
}
}
}
xhttp.open('GET', url, true);
xhttp.send();
function CountryClicked(country){
var div = document.getElementById("parent-country-container")
var h1 = document.createElement("h1")
// div.appendChild(h1)
h1.appendChild(document.createTextNode(country.name + " Clicked"))
div.innerHTML = ""
div.appendChild(h1)
}
Thank you for your time.
It is neccesary to use a closures function to be able to send the right country.
function CountryClicked(el) {
alert(el.name);
}
var countries = [{'flag':'xx',name:'name'}, {'flag':'xx',name:'text 2'}];
var ul = document.getElementById('countries')
for (var i = 0; i < countries.length; i++) { //start iteration
var li = document.createElement("LI")
var img = document.createElement("IMG")
var a = document.createElement("A")
var textNode = document.createTextNode(countries[i].name)
img.setAttribute("src", countries[i].flag)
ul.appendChild(li)
li.appendChild(a)
a.appendChild(img)
a.appendChild(textNode);
a.setAttribute("title", countries[i].name)
var country = countries[i];
a.onclick = (function(country){
return function(){ CountryClicked(country); }
})(country);
}
<ul id="countries"></ul>
I'm want to shorten this function with array
document.mySchedule.breakfast.onchange = function() {
var id = document.mySchedule.breakfast.selectedIndex;
var val = document.mySchedule.breakfast[id].value;
strUser[0]=val;
}
document.mySchedule.lunch.onchange = function() {
var id = document.mySchedule.lunch.selectedIndex;
var val = document.mySchedule.lunch[id].value;
strUser[1]=val;
}
document.mySchedule.dinner.onchange = function() {
var id = document.mySchedule.dinner.selectedIndex;
var val = document.mySchedule.dinner[id].value;
strUser[2]=val;
}
I'm try this way but it didn't seem to be work.
var selectData = ["breakfast","lunch","dinner"]
for(i = 0; i < selectData.lenght; i++) {
document.mySchedule.selectData[i].onchange = function() {
var id = document.mySchedule.selectData[i].selectedIndex;
var val = document.mySchedule.selectData[i][id].value;
strUser[i]=val;
}
}
by the way this use to control selector.
Hope someone can help. thank you
Use:
var selectData = ["breakfast","lunch","dinner"]
for(i = 0; i < selectData.lenght; i++) {
var e = document.getElementById(selectData[i]);
e.onchange = function(){
strUser[i] = e.value;
};
}
I'm trying to make an image slider that changes the image 'displayMain' every few seconds. My problem is that when I call the displayMain function in setInterval, I continuously get a 'cannot read property 0 of undefined' error. Even when I use the hardcoded value of jsonData[i].name, I receive the same error. The value gets passed in displayThumbs just fine, however. Does anyone know why I can't retain the values in displayMain but can do so in displayThumbs?
window.addEventListener('load', function () {
var mainDiv = document.getElementById('main');
var descDiv = document.getElementById('main-description');
var gallery = document.querySelector('#main-img');
var ul = document.querySelector('ul');
var li;
var i = 0;
var displayThumbs;
var thumbName;
var current = 0;
var images = [];
function displayMain () {
var data = images[i];
gallery.src = 'img/' + data[0];
descDiv.innerHTML = '<h2>' + data[1] + '</h2>';
}
function displayThumbs () {
for (i = 0; i < images.length; i += 1) {
var data = jsonData[i].name.replace('.jpg', '_thumb.jpg');
// thumbnails use dom to make img tag
li = document.createElement('li');
thumbs[i] = document.createElement('img');
var createThumbNail = thumbs[i].src = 'img/' + data;
thumbs[i].setAttribute('alt', data);
thumbs[i].addEventListener('click', function() {
alert(createThumbNail);
});
ul.appendChild(thumbs[i]);
}
}
// success handler should be called
var getImages = function () {
// create the XHR object
xhr = new XMLHttpRequest();
// prepare the request
xhr.addEventListener('readystatechange', function () {
if (xhr.readyState === 4 && xhr.status == 200) {
// good request ...
jsonData = JSON.parse(xhr.responseText);
for (var i = 0; i < jsonData.length; i += 1) {
var data = [];
data.push(jsonData[i].name);
data.push(jsonData[i].description);
images.push(data);
}
displayMain();
displayThumbs();
setInterval(displayMain, 1000);
}
else {
// error
}
});
xhr.open('GET', 'data/imagedata.json', true);
xhr.send(null);
};
// setInterval(getImages, 2000);
getImages();
// displayThumbs();
});
Your problem is that your displayMain uses whatever value i is at the time, and i never gets incremented, so it'll be equal to images.length after the for loop in displayThumbs. displayThumbs increments it itself, so you won't ever go beyond the end of the array.
In your comment, you mentioned that you want to cycle through the images. This should work a bit better:
function displayMain () {
var data;
// wrap around to the first image
if (i >= images.length) {
i = 0;
}
data = images[i];
gallery.src = 'img/' + data[0];
descDiv.innerHTML = '<h2>' + data[1] + '</h2>';
i++;
}
Personally, I would use a private i, just in case another function reuses the same variable:
function displayMain () {
var data;
// wrap around to the first image
if (displayMain.i >= images.length || isNaN(displayMain.i)) {
displayMain.i = 0;
}
data = images[displayMain.i];
gallery.src = 'img/' + data[0];
descDiv.innerHTML = '<h2>' + data[1] + '</h2>';
// move to the next image
displayMain.i++;
}
This attaches a variable named i to the function displayMain. It will update this variable each time it is called, and no other function will use the same i variable.
I want to reset new values each time in the option list created JSON by the line:
var o=document.createElement("option");
document.getElementById("shipTo").options.add(o);
o.text= address[i];
But new option values are added in the list I want the no previous in the option:
var counter;
function GetAddress() {
var customerId = document.getElementById("invoiceTo").value;
var xml;
if (window.XMLHttpRequest) {
xml = new XMLHttpRequest();
} else {
xml = new ActiveXObject("Microsoft.XMLHTTP");
}
xml.onreadystatechange = function() {
if (xml.readyState == 4 && xml.status == 200) {
var address = JSON.parse(xml.responseText);
document.getElementById("billingAddress").value = address[0];
document.getElementById("shipAddress").value = address[0];
if (counter == 1) { {
for (var i = 0; i < address.length; i++) {
var removeMe = document.getElementById(o[i]);
removeMe.parentNode.removeChild(removeMe);
var o = document.createElement("option");
document.getElementById("shipTo").options.add(o);
o.text = address[i];
}
}
} else if (counter != 1) {
for (var i = 0; i < address.length; i++) {
var o = document.createElement("option");
document.getElementById("shipTo").options.add(o);
o.text = address[i];
}
}
counter = 1;
}
alert(counter);
}
xml.open("GET", "GenerateInvoice?customerId=" + customerId, true);
xml.send();
}
You need to clear the options first:
var oDDL = document.getElementById("shipTo");
while (oDDL.options.length > 0)
oDDL.options.remove(0);
If I understand correctly, you want to clear all the old options from the select element, before adding new options.
simply set options.length = 0;
example:
var o = document.createElement("option");
theSelect.options.length = 0;
o.text = '400';
theSelect.options.add(o);
http://jsfiddle.net/asaf/77sqX/4/
function GetAddress()
{
var customerId = document.getElementById("invoiceTo").value;
var xml;
if (window.XMLHttpRequest)
{
xml=new XMLHttpRequest();
}
else
{
xml=new ActiveXObject("Microsoft.XMLHTTP");
}
xml.onreadystatechange= function()
{
if(xml.readyState==4 && xml.status==200)
{
var address= JSON.parse(xml.responseText);
document.getElementById("billingAddress").value=address[0];
document.getElementById("shipAddress").value= address[0];
var oDDL = document.getElementById("shipTo");//ship to id of the select in jsp
while (oDDL.options.length > 0)
{
oDDL.options.remove(0);//clears selects option each time
}
for(var i=0;i<address.length;i++)
{
var o = document.createElement("option");//creates optin
document.getElementById("shipTo").options.add(o);//adds option in the list
o.text= address[i];//inserts text in the option
}
}
}
xml.open("GET","GenerateInvoice?customerId="+customerId,true);
xml.send();
}
I have a javascript code with functions:
function convertTime()
function loadZive()
Let's say that I have the following code:
function convertTime(){
alert(exampleVariable);
};
function loadZive(){
var exampleVariable = 3;
convertTime();
};
It looks like my convertTime() function can't access exampleVariable. Is there any workaround?
Here is whole code:
function convertTime(publishedDate){
alert(publishedDate);
var date = publishedDate;
var publishedDay = date.toLocaleDateString();
var publishedHour = date.getHours(); //nemozno pouzit toLocaleTimeString (cielovy format ma byt bez sekund)
if (publishedHour < 10){
publishedHour = "0" + publishedHour;
};
var publishedMinute = date.getMinutes(); //nacitanie hodin a minut
if (publishedMinute < 10){
publishedMinute = "0" + publishedMinute;
};
var publishedTime = publishedHour +":"+ publishedMinute; //ich nasledne spojenie do casoveho formatu HH:MM
var publishedDateConverted = publishedDay +", "+ publishedTime;
};
function loadZive(publishedDateConverted){
google.load("feeds", "1");
function initialize() {
var feed = new google.feeds.Feed("http://www.zive.sk/rss/sc-47/default.aspx");
feed.setNumEntries(window.localStorage.getItem("entriesNumber"));
feed.load(function(result) {
if (!result.error) {
var feedlist = document.getElementById("feedZive");
for (var i = 0; i < result.feed.entries.length; i++) {
var li = document.createElement("li");
var entry = result.feed.entries[i];
var A = document.createElement("A");
var descriptionSettings = window.localStorage.getItem("descriptionSettings");
if (descriptionSettings=="true"){
var h3 = document.createElement("h3");
var p = document.createElement("p");
var pDate = document.createElement("p");
pDate.setAttribute("class","ui-li-aside");
var publishedDate = new Date(entry.publishedDate);
convertTime();
pDate.appendChild(document.createTextNode(publishedDateConverted));
h3.appendChild(document.createTextNode(entry.title));
p.appendChild(document.createTextNode(entry.content));
A.setAttribute("href",entry.link);
A.appendChild(h3);
A.appendChild(p);
A.appendChild(pDate);
}
else{
A.setAttribute("href",entry.link);
A.appendChild(document.createTextNode(entry.title));
};
li.appendChild(A);
feedlist.appendChild(li);
}
$("#feedZive").listview("refresh");
}
});
}
google.setOnLoadCallback(initialize);
};
Alert result is Undefined.
PS: exampleVariable isn't defined by the user; it is loaded from a feed, so I cannot define it before the convertTime() function.
As Danny said, or you can also pass variables this way:
function convertTime(exampleVariable){
alert(exampleVariable);
};
function loadZive(){
var exampleVariable = 3;
convertTime(exampleVariable);
};
Remove var from loadZive(), this makes the variable local to loadZive() only.
Alternatively, pass exampleVariable as a parameter to convertTime().