Convert comma separated list to Unordered List [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Looking for any PHP, Jquery, javascript solution to take data separated by commas and turn it into an unordered list.
To explain further, I have imported a CSV file into wordpress and one element block contains lots of data that is comma separated and I need it to display as a list.
All help is appreciated!

In PHP
$list = 'item1,item2,item3,item4';
$list = explode(',', $list);
shuffle($list);
$html = '<ul>';
foreach($list as $item) {
$html .= '<li>' . $item . '</li>';
}
$html .= '</ul>';
print $html;
In JavaScript
var list = 'item1,item2,item3,item4';
list = list.split(',');
list.sort(function() { return 0.5 - Math.random() });
var html = '<ul>';
for(var i=0; i<list.length; i++) {
html += '<li>' + list[i] + '</li>';
}
html += '</ul>';

There are cleaner ways to write this, but hopefully this will give you an idea of how it can be done using jQuery.
$(function(){
$csv = $("#csv")
items = $csv.text().split(",")
$csv.replaceWith($("<ul/>"))
items.forEach(function(item){
$("ul").append("<li>"+item+"</li>")
})
})
And here's the fiddle: http://jsfiddle.net/JmwDw/

HTML
<ul id="ul-test">
</ul>
JavaScript
var CSV = "a,b,c,d,e";
var arrCSV = CSV.split(','),
ul = document.getElementById("ul-test");
for (var i = 0, len = arrCSV.length; i < len; i++) {
var li = document.createElement("li");
var text = document.createTextNode(arrCSV[i]);
li.appendChild(text);
ul.appendChild(li);
}
JSFiddle

Related

Deleting items stored

I'm creating a multiple choice quiz which allows users to insert their own questions and answers and from there create a quiz. I can't think how I could let users delete questions stored in the question bank.
bodyText = bodyText + '<p>Questions currently in the question bank:</p>';
bodyText = bodyText + '<ul>';
for(var i=0; i<questionBank.length;i++) {
// loop through the quiz bank and display each question text for review
bodyText = bodyText + '<li>' + questionBank[i]['questionText'] + '</li>';
}
bodyText = bodyText + '</ul>';
bodyText = bodyText + '<p>Create the quiz, delete or add more questions. </p>';
}
If you also create a button to attached an action too, you can capture the [i] and use it to splice, remove, push, pop, whichever you choose.
bodyText = bodyText + '<p>Questions currently in the question bank:</p>';
bodyText = bodyText + '<ul>';
for(var i=0; i<questionBank.length;i++) {
// loop through the quiz bank and display each question text for review
bodyText = bodyText + '<li>' + questionBank[i]['questionText'] + '</li>'
<button onClick={delete questionBank[i]}>Delete me</button>;
}
bodyText = bodyText + '</ul>';
bodyText = bodyText + '<p>Create the quiz, delete or add more questions. </p>';
}
my button is sudo code!!! It sounds like you might be new to programming, have fun with this. The basic idea is inside that for loop, you can use the [i] or index for each item you're rendering.

How to fill an array into a HTML table [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to fill my HTML table with my array. I tried it with $rowTemplate.find('[data-id=id]').text(id);
But it didn't work. I work with sockets so I can't post all of my code that would be too confusing.
I will ads some of my code but it's a general question how to fill a HTML table with input of an two dim array.
socket.on('outputData', function(data) {
var $rowTemplate = $('<tr><td data-id="id"></td><td data-id="name"></td><td data-id="geburtsort"></td><td data-id="geburtsdatum"></td><td data-id="favorite"></td></tr>');
var resultArray = data.resultArray;
var name, location, bdate, id, anzahl = 0;
for (var i = 0; i < resultArray.length; i++) {
name = resultArray[i][0];
anzahl = anzahl + 1;
console.log(name);
location = resultArray[i][1];
bdate = resultArray[i][2];
favorit = resultArray[i][3];
id = resultArray[i][4];
$rowTemplate.find('[data-id=id]').text(id);
$rowTemplate.find('[data-id=name]').text(name);
$rowTemplate.find('[data-id=geburtsort]').text(location);
$rowTemplate.find('[data-id=geburtsdatum]').text(bdate);
}
$("#table > tbody").append(rowTemplate.html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<table id="table">
<tbody>
<tr>
<th>ID</th>
<th>Name</th>
<th>Geburtsort</th>
<th>Geburtsdatum</th>
<th>Favorit</th>
</tr>
</tbody>
</table>
The problem lies with your variable rowTemplate. Get rid of the $ and it should work.
var rowTemplate = $('<tr><td data-id="id"></td><td data-id="name"></td><td data-id="geburtsort"></td><td data-id="geburtsdatum"></td><td data-id="favorite"></td></tr>');
rowTemplate.find("[data-id=id]").text("bcd");
Test it out here: https://jsfiddle.net/Lwmu4p6q/
I am not quite sure why that is the case, though. I think it is problematic because of jQuery. You can still use variables starting with a dollar sign, but when you start cascading with jQuery functions, it doesn't seem to work.
EDIT: Another way to do it would be to manually "build up" the row.
Instead of parsing the HTML with jQuery like rowTemplate = $('...'); and then manipulating it with jQuery selectors you could do it like this with vanilla JavaScript:
var outputHTML = "";
for (var i = 0; i < array.length; i++) { // i for the rows
var newRow = "<tr>";
for (var j = 0; j < array[i].length; j++) { // j for the colums
newRow += "<td>" + array[i][j] + "</td>";
}
outputHTML += newRow + "</tr>";
}
I would suggest using let instead of var if possible. And I would argue that this version might perform faster, but the difference, if existent at all, would only matter with really big tables. It depends on the way jQuery selectors and text() has been implemented, though.
EDIT 2:
Check https://jsfiddle.net/Lv9vdv8u/ for the second version.

Javascript/JQuery Dynamic UL Troubles

I have been working on a problem adding dynamic UL and LI's to a webpage through javascript and jQuery and am stumped.
I almost have a solution but it's not adding the styling and it is not putting each UL on a separate line. I have a feeling that the tags I am creating are not closing but I'm not sure.
My end goal is to have each JSON line as a separate UL and showing on a separate line, with the first name + last name + phone number as the list items of each UL and displaying like a table (without using a table). No inline styles and no HTML markup other than whatever is added dynamically through Javascript.
I was given the following code as a starting point but my solution has definitely veered a little off course. I have searched for hours and so far you can see my best attempt at the jsfiddle link below. Any help is greatly appreciated.
function showContacts(data){
var markup = "";
$("body").html(markup);
};
$(document).ready(function myFunction() {
var jsonText = '[ {"firstname":"Bill","lastname":"Gates","phone":"123-456-7891"}, {"firstname":"Steve","lastname":"Jobs","phone":"198-765-4321"}, {"firstname":"Kevin","lastname":"Spencer","phone":"007-008-0099"}, {"firstname":"David","lastname":"Zimmerman","phone":"800-256-6321"}, {"firstname":"Bert","lastname":"Ernie","phone":"127-624-1138"}, {"firstname":"Guy","lastname":"Lafleur","phone":"806-797-4213"} ]';
showContacts(jsonText);
});
https://jsfiddle.net/bkweLctq/embedded/result/
You just missed element creation.
Your odd & even class style also needs to be changed.
Updated js
function showContacts(data) {
var markup = "";
var jo = $.parseJSON(data);
console.log(jo);
var $body = $('body');
var _html = '';
for(var i = 0; i<jo.length; i++){
if((i+1)%2 == 0 ){
_html += '<ul class="even">';
}else {
_html += '<ul class="odd">';
}
var _index = 0;
$.each(jo[i], function(k,n) {
if((_index+1)%2 == 0 ){
_html += '<li class="even"> '+ n +' </li>'
}else {
_html += '<li class="odd"> '+ n +' </li>'
}
_index++;
});
_html += '</ul>';
}
$body.html(_html);
};
$(document).ready(function myFunction() {
var jsonText = '[ {"firstname":"Bill","lastname":"Gates","phone":"123-456-7891"}, {"firstname":"Steve","lastname":"Jobs","phone":"198-765-4321"}, {"firstname":"Kevin","lastname":"Spencer","phone":"007-008-0099"}, {"firstname":"David","lastname":"Zimmerman","phone":"800-256-6321"}, {"firstname":"Bert","lastname":"Ernie","phone":"127-624-1138"}, {"firstname":"Guy","lastname":"Lafleur","phone":"806-797-4213"} ]';
showContacts(jsonText);
});
I have also updated your fiddlejs link

Why doesn't my local storage work? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I am trying to localStore the history but it does not work. I tried JSON.stringify and a script called JStorage but I couldn't get either to work.
function updateHistory(video) {
getHistory();
blacklist[video["id"]] = true;
myhistory.push(video);
var html = "<li class=\"history\">" +
"<img class= \"img-rounded\" src=\"{0}\"/>" +
"<p><b title=\"{2}\"><a class=\"extendedLink\" href=\"javascript:watchHistoricVideo(\'{1}\');\"><span></span>{2}</a></b><br>" +
"by {3}<br>" +
"{4} | {5} views</p>" +
"</li>";
$("#myhistory").prepend(html.format(video["thumbnail"],
video["id"],
video["title"],
video["uploader"],
video["length"],
video["views"]));
saveHistory();
}
function saveHistory() {
localStorage.setItem(myhistory, myhistory.innerHTML);
}
(The alert does show up)
function getHistory() {
localStorage.getItem(myhistory);
alert("working");
}
The point is, instead of storing the html part you better store the video object instead, you can store videos based on their id, and instead of array use javascript object:
function setVideo(video) {
var videos = JSON.parse(localStorage.getItem("myhistory") || "{}");
videos[video["id"]]=video;
localStorage.setItem("myhistory", JSON.stringify(videos));
}
function getVideos() {
var myhistory = localStorage.getItem("myhistory");
if(!myhistory) return {};
else return JSON.parse(myhistory);
}
function getVideo(id) {
var myhistory = localStorage.getItem("myhistory");
if(!myhistory) return null;
var videos = JSON.parse(myhistory);
return videos[id] || null;
}
now you can use getVideo to retrieve the video object by id.you can separate the part which shows the video, like:
function showVideo(video) {
blacklist[video["id"]] = true;
var html = "<li class=\"history\">" +
"<img class= \"img-rounded\" src=\"{0}\"/>" +
"<p><b title=\"{2}\"><a class=\"extendedLink\" href=\"javascript:watchHistoricVideo(\'{1}\');\"><span></span>{2}</a></b><br>" +
"by {3}<br>" +
"{4} | {5} views</p>" +
"</li>";
$("#myhistory").prepend(html.format(video["thumbnail"],
video["id"],
video["title"],
video["uploader"],
video["length"],
video["views"]));
}
let's say you want to show the whole videos in the history:
var videos = getVideos();
for(var id in videos){
showVideo(videos[id]);
}

Generate a list [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
So I want to generate a list from an Array I wrote the following code:
function list() {
table = new Array("Rabat", "Casablanca", "Marrakech", "Fes", "Tanger", "Agadir");
document.write('<select id="list1" size=6><option value="Rabat">Rabat</option><option value="Casablanca">Casablanca</option></select>');
}
It works but I'm wondering if there's a better coding
You can use a loop to go through all items in the list:
// you can use this instead of the new Array() syntax:
var table = ["Rabat", "Casablanca", "Marrakech", "Fes", "Tanger", "Agadir"];
var select = '<select id="list1" size="6">';
for (var i=0; i<table.length; i++) {
select += '<option value="' + table[i] + '">' + table[i] + '</option>';
}
select += '</select>';
document.write(select); //you should probably not use document.write though...
Usually it is better not to use document.write though. Instead, you should try selecting the element you want to append to, and then add the text to that.
HTML:
<select id="list1" size="6"></select>
JS:
function list() {
var i,
table = ["Rabat", "Casablanca", "Marrakech", "Fes", "Tanger", "Agadir"],
select = document.getElementById('list1'),
out;
for (i = 0; i < table.length; ++i) {
out += "<option value='" + table[i] + "'>" + table[i] + "</option>";
}
select.innerHTML = out;
}
FIDDLE:
http://jsfiddle.net/Z9XKp/
you can loop over the array and make your string rather than writing same code again and again .
var list="";
for(i=0;i<table.length;i++){
var val=table[i];
list+="<option value='"+val+"'>"+val+"</option";
}

Categories

Resources