I have a problem with listview.
I'm filling the list with an array, this list is completely custom, and I want that if an element of this array begins with "-R", then that cell must be different from the others (color, font, etc.).
the problem is that I can not take the index of the cell that begins with "-R".
this is the code:
arrayEserCardio = "try;find;-Reply;Again;"
var indexEserSplit = arrayEserCardio.toString().split(";");
for (var i =0; i<indexEserSplit.length;i++) {
var eserSingle = indexEserSplit[i];
var link_markup ='<li id="listCardio2"><a onclick="rowSelectedEserCardio()" href="#" class="ui-link-inherit"><div class="textScheda"><p style="white-space: normal" class="titleEs">'+eserSingle+'</p></div></a></li>';
if(eserSingle.substring(0,2)=='-R') {
var initial = eserSingle.substring(0,2);
var index = arrayEserCardio.indexOf(initial);
//but index return wrong
}
}
I hope I was clear, I do not know javascript very well.. thanks to all
I would write it like this:
var
arrayEserCardio = "try;find;-Reply;Again;",
var indexEserSplit = arrayEserCardio.split(";"),
eserSingle,
link_markup,
i;
for (var i = 0; i < indexEserSplit.length; i++) {
eserSingle = indexEserSplit[i];
cls = "titleEs";
if (eserSingle.substring(0,2) == '-R') {
cls += " with_min_r";
}
link_markup ='<li id="listCardio2"><a onclick="rowSelectedEserCardio()" href="#" class="ui-link-inherit"><div class="textScheda"><p style="white-space: normal" class="' + cls + '">' + eserSingle + '</p></div></a></li>';
}
It should have been
if (eserSingle.substring(0, 2).equals("-R")) {
}
The == operator compares the object references, not the value of the Strings.
Related
I have been struggling to find a way in which I could sort Divs after being displayed .So far, I have used prepend() and append() and I have managed to show at first the players that are streaming, but the next divs are random. I want to be able to show who's online, who's not and who has closed the account in order.
I have already tried deferred method: $.when(makeDivs()).then(sortDivs());
but it's not working properly, any idea how I can fix this?
My codepen: http://codepen.io/diegomdzr/pen/vKWGbd
I don't have the reputation to comment yet. But from my understanding, you want to make the classNames of divs in alphabetical order after they have been applied to the document?
function reOrder() {
var div = document.getElementsByTagName('div');
var cn = []; //ClassNames of each div.
for (var i = 0; i < div.length; i++) {
cn.push(div[i].className);
}
cn = cn.sort(); //sort the array in alphabetical order.
var oDiv = [];
for (var i = 0; i < cn.length; i++) {
//for each array item in cn, find where it's element is, remove the element, continue.
for (var ii = 0; ii < div.length; ii++) {
if (div[ii].className == cn[i]) {
oDiv.push(div[ii]);
var newDiv = [];
for (var iii = 0; iii < div.length; iii++) {
//Remove the element from the array.
if (div[iii] != div[ii]) {
newDiv.push(div[iii]);
}
}
div = newDiv;
}
}
}
return oDiv;
};
reOrder();
This will return an array of the elements, but sorted. You can then replace all of the elements of the document with these sorted elements.
Sorting is expensive, should be avoided if possible, and isn't a particularly good solution here.
It's way simpler to create a container (div) for each of your streamer categories, (online|offlie|nonExistent) then simply append HTML, as it is generated, to the appropriate container.
$(document).ready(function() {
var streamers = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas", "comster404", "brunofin", "HorussTV"];
var link = "https://twitch.com/";
// Create/append containers here (or hard-code them in HTML) ... in correct order of presentation within #streamers.
var $onlineStreamers = $("<div/>").appendTo($('#streamers'));
var $offlineStreamers = $("<div/>").appendTo($('#streamers'));
var $nonExistantStreamers = $("<div/>").appendTo($('#streamers'));
streamers.forEach(function getStatus(element) {
$.getJSON("https://api.twitch.tv/kraken/channels/" + element + "?callback=?", function(json) {
var img = json.logo || "http://res.cloudinary.com/djnwhbm1z/image/upload/v1468187598/unknown_i7m43p.png";
$.getJSON("https://api.twitch.tv/kraken/streams/" + element + "?callback=?", function(json) {
// Append HTML to the appropriate container
if(json.stream) {
$onlineStreamers.append('<div class="online"><h4>' + element + '</h4><img src="' + img + '" class="profPic"><div class="content text-center"><span><b>Game:</b></br>' + json.stream.game + ' </br><b>Status: </b>' + json.stream.channel.status + '</span></div></div>');
} else if(json.status == 422) {
$nonExistantStreamers.append('<div class="nonExistant"><h4>' + element + '</h4><img src="' + img + '" class="profPic"><div class="content text-center"><span>Account Closed</span></div></div>');
} else {
$offlineStreamers.append('<div class="offline"><h4>' + element + '</h4><img src="' + img + '" class="profPic"><div class="content text-center"><span>Offline</span></div></div>');
}
});
});
});
});
Notes:
No sorting required unless the entries need to be sorted within each category.
You can probably purge class="online" etc from the appended HTML, unless those classes are used elsewhere.
I have been experimenting with this code http://mounirmesselmeni.github.io/2012/11/20/javascript-csv/ to get data from a text file. (Working demo here: http://mounirmesselmeni.github.io/html-fileapi/).
It works well for reading files, but I am stumped about how to get the data into an array. It seems as though it is reading everything into the "lines" array, but I can't work out how to use it.
I tried modifying it like this:
function processData(csv) {
var allTextLines = csv.split(/\r\n|\n/);
var lines = [];
var myArray = [];
while (allTextLines.length) {
lines.push(allTextLines.shift().split(','));
myArray.push(allTextLines.shift().split(',')); //put data into myArray
}
function myFunction() { //display myArray in "demo"
var index;
for (index = 0; index < myArray.length; index++) {
text += myArray[index];
}
document.getElementById("demo").innerHTML = text;
}
but that didn't work. I know I am missing something simple here, but this has me stumped.
Currently you modify the array twice:
lines.push(allTextLines.shift().split(',')); // shift modifies the array
myArray.push(allTextLines.shift().split(',')); //gets the shifted array
You might want to try putting this in temp variable:
var line = allTextLines.shift().split(',');
lines.push(line);
myArray.push(line);
Try
csv.split(/\r\n|\n|,/).map(function(value, index) {
demo.innerHTML += "\n" + value.trim()
});
var csv = 'Year,Make,Model,Description,Price'
+ '1997,Ford,E350,"ac, abs, moon",3000.00'
+ '1999,Chevy,"Venture ""Extended Edition""","",4900.00'
+ '1999,Chevy,"Venture ""Extended Edition, Very Large""",,5000.00'
+ '1996,Jeep,Grand Cherokee,"MUST SELL!'
+ 'air, moon roof, loaded",4799.00',
demo = document.getElementById("demo");
csv.split(/\r\n|\n|,/).map(function(value, index) {
demo.innerHTML += "\n" + value.trim()
})
<div id="demo"></div>
I'm trying to loop through an Array which then uses innerHTML to create a new element for every entry in the array. Somehow my code is only showing the last value from the array. I've been stuck on this for a few hours and can't seem to figure out what I'm doing wrong.
window.onload = function() {
// Read value from storage, or empty array
var names = JSON.parse(localStorage.getItem('locname') || "[]");
var i = 0;
n = (names.length);
for (i = 0; i <= (n-1); i++) {
var list = names[i];
var myList = document.getElementById("list");
myList.innerHTML = "<li class='list-group-item' id='listItem'>"+ list + "</li>" + "<br />";
}
}
I have a UL with the id 'list' in my HTML.
Change your for loop:
for (i = 0; i <= (n-1); i++) {
var list = names[i];
var myList = document.getElementById("list");
myList.innerHTML += "<li class='list-group-item' id='listItem'>"+ list + "</li>" + "<br />";
}
Use += instead of =. Other than that, your code looks fine.
I suggest you to first make a div by create element. there you add your innerHTML and after that you can do the appendchild. That will work perfectly for this type of scenario.
function displayCountries(countries) {
const countriesDiv = document.getElementById('countriesDiv');
countries.forEach(country => {
console.log(country.borders);
const div = document.createElement('div');
div.classList.add('countryStyle');
div.innerHTML = `
<h1> Name : ${country.name.official} </h1>
<h2> Capital : ${country.capital} </h2>
<h3> Borders : ${country.borders} </h3>
<img src="${country.flags.png}">
`;
countriesDiv.appendChild(div);
});
}
I have a page that contains several divs. The divs have the same postfixes but different prefixes. What I want to do is loop through them and if one of them contain a 0 hide the description div.
The divs look like this:
<div id="first_desc">First</div><div id="first_note1">0</div>
<div id="second_desc">Second</div><div id="second_note1"></div>
<div id="third_desc">Third</div><div id="third_note1"></div>
My script is this:
$(document).ready(function() {
// Variables
var firstdiv = 'first';
var seconddiv = 'second';
var thirddiv = 'third';
// Array
var myArray = new Array(firstdiv, seconddiv, thirddiv);
for(var x = 0; x < myArray.length; x++) {
if('$("#' + myArray[x] + '_note1").text() === $.trim("0")') {
'$("#' + myArray[x] + '_desc").hide()';
}
}
});
So far this code is not working. Can anyone help me? Thanks.
You have some extra ' in there.
if($("#" + myArray[x] + "_note1").text() === $.trim("0")) {
$("#" + myArray[x] + "_desc").hide();
I'm using a simple JS duplicate function to duplicate a div. Inside is form information with radio buttons, including one group called 'getOrRequest'. Each div represents a book and needs to have its own 'getOrRequest' value.
The name needs to be changed in order to make each duplicated group of radio buttons selectable without affecting every other radio button. What is the best way to change these values?
Here is how I'm duplicating the div, in case that is the issue.
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
bookInfo.appendChild(copyDiv);
I then have tried a couple methods of changing the name value. Like this:
bookInfo.copyDiv.getOrRequest_0.setAttribute("name", "'getOrRequest' + idNumber + '[]'");
bookInfo.copyDiv.getOrRequest_1.setAttribute("name", "'getOrRequest' + idNumber + '[]'");
As well as this:
bookInfo.copyDiv.getOrRequest_0.name = 'getOrRequest' + idNumber + '[]';
bookInfo.copyDiv.getOrRequest_1.name = 'getOrRequest' + idNumber + '[]';
getOrRequest_0 and getOrRequest_1 are the ID's of the input values, but I've tried it a few ways now and nothing seems to work. Thanks in advance!
EDIT: MORE INFO
Here is the specific code I'm using:
function addAnotherPost(){
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
var size = copyDiv.childNodes.length;
copyDiv.id = 'addListing' + idNumber;
for(var j = 0; j < size; j++){
if(copyDiv.childNodes[j].name === "getOrRequest[]"){
copyDiv.childNodes[j].name = "getOrRequest" + idNumber + "[]";
}
}
bookInfo.appendChild(copyDiv);
idNumber++;
}
And it just doesn't seem to work.. The divs are duplicating, but the name value is not changing.
You can try this - http://jsfiddle.net/ZKHF3/
<div id="bookInformation">
<div id="addListing">
<input type="radio" name="addListing0[]" />
<input type="radio" name="addListing0[]" />
</div>
</div>
<button id="button">Add Listing</button>
<script>
document.getElementById("button").addEventListener("click", AddListing, false);
var i = 1;
var bookInfo = document.getElementById('bookInformation');
function AddListing() {
var copyDiv = document.getElementById('addListing').cloneNode(true);
var size = copyDiv.childNodes.length;
copyDiv.id = "listing" + i;
for ( var j = 0; j < size; j++ ) {
if ( copyDiv.childNodes[j].nodeName.toLowerCase() == 'input' ) {
copyDiv.childNodes[j].name = "addListing" + i + "[]";
}
}
bookInfo.appendChild(copyDiv);
i++;
}
</script>
The trouble is you are looking for child nodes of the div, but the check boxes are not child nodes, they are descendant nodes. The nodes you are looking for are nested within a label. Update your code to look for all descendant inputs using copyDiv.getElementsByTagName("input"):
var idNumber = 0;
function addAnotherPost() {
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
copyDiv.id = 'addListing' + idNumber;
var inputs = copyDiv.getElementsByTagName("input");
for(var j = 0; j < inputs.length; j++){
if(inputs[j].name === "getOrRequest[]"){
inputs[j].name = "getOrRequest" + idNumber + "[]";
}
}
bookInfo.appendChild(copyDiv);
idNumber++;
}
http://jsfiddle.net/gilly3/U5nsa/