Generate a list [closed] - javascript

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";
}

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.

Dynamically load Two Questions into separate forms as well as their appropriate answer options

I'm trying to have a button, that once pressed. Dynamically loads Two Questions (question1, and question2) into separate forms. But it also contains the questions 3 Answers to choose from. Currently my for loop adds an additional set of 3 answers(question 2's answers) to choose from to Question 1
OUTPUT Looks like the following :
It needs to be QUESTION 1 (YES, NO, OTHER) and QUESTION 2 (YES2, NO2, OTHER2)
CODE
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="center col-xs-12">
<button class="contentBtn btn"><label for="contentBtn">CONTENT</label></button>
</div>
<div class="row-2 center col-xs-12"></div>
<script src="js/jquery-1.11.3.min.js" type='text/javascript'>
</script>
<script>
$('.contentBtn').click(function(){
var contentArray = [
["QUESTION1?", "YES", "NO", "OTHER"],
["QUESTION2?", "YES2", "NO2", "OTHER2"]
];
for (var i = 0; i < contentArray.length; i++){
$('.row-2').append("<form><span class='question'>" + contentArray[i][0] + "<\/span><br>")
for (var x = 1; x < 4; x++){
$('form').append("<input type='radio' value='" + contentArray[i][x] + "'>" + contentArray[i][x] + "");
}
$('.row-2').append("<\/form><br>");
}
});
</script>
</body>
</html>
The short answer is that you are appending 'form', meaning you are appending every form on the DOM. The code is also corrupting the DOM. The inputs are not closed, and append should never be done in partials like given in the example.
// Always favor the 'on' events instead of the 'click' events.
$('.contentBtn').on('click', function () {
var contentArray = [
['QUESTION1?', 'YES', 'NO', 'OTHER'],
['QUESTION2?', 'YES2', 'NO2', 'OTHER2']
];
// we are going to use a for each on the first item,
// we could use a for as well but it just is really messy.
// remember that variables are defined at function scope, not block scope.
$(contentArray).each(function (index, item) {
// our item in the array is directly coming in to us now.
// do not add incomplete html blocks to the dom, always
// create them and then add them!
var newContent = $('<form><span class="question">' +
item[0] + '</span><br></form><br>');
// now we will foreach, but instead of going by a length of 4,
// I am looking at the actual length of the array.
for (var i = 1; i < item.length; i++) {
// we are going to precreate our dom object.
var answerContent = $('<input type="radio" value="' +
item[i] + '">' + item[i] + '</input>');
// now we are going to append the object to our form object.
newContent.append(answerContent);
}
// now that the structure is complete we will append the browser dom.
$('.row-4').append(newContent);
});
});
I have created a corrected fiddle with comments for you.
https://jsfiddle.net/t9h91nbk/
Hope this helps.
The problem is in this line :
$('form').append("<input type='radio' value='" + contentArray[i][x] + "'>" + contentArray[i][x] + "");
The javascript can't detect wich form you want to append input to it so it will append to all the forms in page, so you have to add an identifier to the form you create.
I'll add class to identify each form and append the input using this identifiers :
$('.row-2').append("<form class='form_"+i+"'><span class='question'>" + contentArray[i][0] + "</span><br>")
for (var x = 1; x < 4; x++){
$('.form_'+i).append("<input type='radio' value='" + contentArray[i][x] + "'>" + contentArray[i][x] + "");
}
Hope this helps.
Working fiddle

Convert comma separated list to Unordered List [closed]

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

How to iterate a List of HashMap in jQuery [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I've a requirement where in I receive a List of HashMap from a database query and I've to display that on the JSP.
The JSON object looks like below:
[
{"UNIT_NM":"ATLANTA", "UNIT_CD":"A00"},
{"UNIT_NM":"ATLANTA CKO","UNIT_CD":"A00"},
{"UNIT_NM":"DALLAS", "UNIT_CD":"D00"},
{"UNIT_NM":"DALLAS CKO", "UNIT_CD":"D00"}
]
I've to display it in dropdown like:
"<option value='A00'> A00 ATLANTA</option>";
"<option value='A00'> A00 ATLANTA CKO</option>";
"<option value='D00'> D00 DALLAS</option>";
"<option value='D00'> D00 DALLAS CKO</option>";
The JS code is:
$.ajax({
url:indexContextRoot+"populateManualCsoCodes",
type:"post",
async:true,
success: function(data){
var listItems= "<option value=''>Please Select</option>";
$.each(data, function(key, value) {
listItems+= "<option value='" + key + "'>" + value + "</option>";
});
$("#manualCsoCodes").html(listItems);
}
});
I'm getting the dropdown as:
[object][Object]
[object][Object]
[object][Object]
[object][Object]
Any suggestions please!
The each() callback function has two parameters: 1) The index of the array element, and 2) The array element. So key is going to be 0, 1, 2, etc. and value is going to be the js object at that index position. So you need to do:
$.each(data, function(key, obj) {
var str = obj["UNIT_CD"];
listItems+= "<option value='" + str + "'>" + str + " " + obj["UNIT_NM"] + "</option>";
});
To make this a bit more modular and involve lesser HTML, here's my take on this :
var data = [
{
"UNIT_NM": "ATLANTA",
"UNIT_CD": "A00"
},
{
"UNIT_NM": "ATLANTA CKO",
"UNIT_CD": "A00"
},
{
"UNIT_NM": "DALLAS",
"UNIT_CD": "D00"
},
{
"UNIT_NM": "DALLAS CKO",
"UNIT_CD": "D00"
}
];
//init first option
var $option = $("<option/>", {
"value": '',
"html": "Please Select"
});
//add that to an array
var options = [$option];
//iterate over data
$.each(data, function (key, value) {
// value now contains a row eg., when key = 0, value = { "UNIT_NM": "ATLANTA", "UNIT_CD": "A00" }
//clone the default option, change the value and the HTML, then push into options array
options.push($option.clone().val(value.UNIT_CD).html(value.UNIT_CD + " " + value.UNIT_NM));
});
//add that array into select
$("#manualCsoCodes").html(options);
The idea is to create an options array, which fills up with jQuery objects with tag name option and then place that in the select tag. Here's a demo
Oh, before i forget, each iterates row-wise. So, in any iteration of each, you'll get a row of data. For example,
if key === 2, then value === {
"UNIT_NM": "DALLAS",
"UNIT_CD": "D00"
}
So, to access UNIT_NM & UNIT_CD, you'll have to use value.UNIT_NM & value.UNIT_CD respectively. For more info on each, see docs.
Hope that helps!
listItems+= "<option value='" + value.UNIT_CD + "'>" + value.UNIT_CD + " " + value.UNIT_NM + "</option>";
PS: you could do that yourself if you used console.log(value);

Categories

Resources