Html select options appending - javascript

I am using the below code to convert the blockquote to the options of select element.
Please help to make it right as each option. Thank you.
["Yes ↵No", "one ↵two ↵three ↵four", "person 1 ↵person 2"]
var newArr = [];
for (var i = 0; i < arr.length; i++) {
var data = arr[i].split('\r\n');
newArr.push(data);
}
for (var j = 0; j < newArr.length; j++) {
$('#metadata-field').append('<select name=""></select>');
if (newArr[j].length) {
for (var k = 0; k < newArr[j].length; k++) {
$('#metadata-field select').append('<option>' + newArr[j][k] + '</option>');
}
} else {
alert('No data');
}
}

Try this : You need to split array element using ↵ and then append each element using one loop only and not nested loop. See below code -
var arr = ["Yes ↵No", "one ↵two ↵three ↵four", "person 1 ↵person 2"]
for (var i = 0; i < arr.length; i++) {
var data = arr[i].split(' ↵');
//create select box
var $select = $('<select id="' + i + '"></select>');
$('#metadata-field').append($select);
for(var k=0;k<data.length;k++)
{
//append options in select box
$select.append('<option>' + data[k] + '</option>');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="metadata-field"></div>

Related

Can't get JSON string's element

I'm totally new to javascript and I'm trying to display an array of object which is stored in local storage using javascript and html and display each element of the JSON string in td tag of a table
In studentList.js file, first of all, I create a Student object:
function Student(id, name, birthDay, gender, falcuty, point ) {
this.id = id
this.name = name
this.birthDay = birthDay
this.gender = gender
this.falcuty = falcuty
this.point = point
}
var table = document.getElementById("table-stud")
And an array of 'Student' object:
var collection = [];
collection.push(new Student("01","A","20/11/1998","M","IT","8.0"),
new Student("02","B","2/1/1998","F","IT","8.0"),
new Student("03","C","9/9/1997","F","CK","8.8"))
Save student in local storage:
function saveStudent(collection) {
for(var i = 0; i < collection.length; i++) {
var studentObjectSerialiseData = JSON.stringify(collection[i])
console.log(studentObjectSerialiseData)
window.localStorage.setItem("student"+i, studentObjectSerialiseData)
}
}
Display students:
function getStudents() {
console.log(Student.length)
for(var i = 0; i < collection.length; i++) {
var studentObjectSerialiseData = window.localStorage.getItem("student"+i)
var temp = JSON.parse(studentObjectSerialiseData)
var tr = document.createElement("tr")
for(var j = 0; j < Student.length; j++) {
var td = document.createElement("td")
td.innerText = temp[j]
tr.appendChild(td)
}
table.appendChild(tr)
}
}
saveStudent(collection);
getStudents();
In HTML file, I called studentList.js file and added id to the 'table' tag, the localStorage worked perfectly but when I want to display, this happened:
id Name birthDay Gender Falcuty Point
undefined undefined undefined undefined undefined undefined
undefined undefined undefined undefined undefined undefined
undefined undefined undefined undefined undefined undefined
Please help me solve this problem!
The problem is mostly on the parts you're trying to loop over the keys of Student. Utilize Object.keys for achieving it instead:
function getStudents() {
for (var i = 0; i < collection.length; i++) {
var studentObjectSerialiseData = window.localStorage.getItem("student" + i)
var temp = JSON.parse(studentObjectSerialiseData)
var tr = document.createElement("tr")
for (var j = 0; j < Object.keys(temp).length; j++) {
var td = document.createElement("td")
console.log(temp)
td.innerText = temp[Object.keys(temp)[j]]
tr.appendChild(td)
}
table.appendChild(tr)
}
}
For a working example, see this snippet: https://jsbin.com/koqikiquzu/1/edit?html,js,output (Tried to embed through SO's own playground, but using localStorage is a bit tricky here).
temp in getStudents() is an object so you need to loop over that too.
function getStudents() {
for (var i = 0; i < collection.length; i++) {
var studentObjectSerialiseData = window.localStorage.getItem("student" + i)
var temp = JSON.parse(studentObjectSerialiseData)
var tr = document.createElement("tr")
for (var j = 0; j < Student.length; j++) {
for(var i in temp) {
var td = document.createElement("td")
td.innerText = temp[i]
tr.appendChild(td)
}
}
table.appendChild(tr)
}
}
You can get the result by using for in loop inside j for loop and appends to tr tag if j and i are equal.
function getStudents() {
for (var i = 0; i < collection.length; i++) {
var studentObjectSerialiseData = window.localStorage.getItem("student" + i);
var temp = JSON.parse(studentObjectSerialiseData);
var tr = document.createElement("tr");
for (var j = 0; j < Student.length; j++) {
for (x in temp) {
if (j == i) {
var td = document.createElement("td");
td.innerText = (temp)[x];
tr.appendChild(td);
}
}
}
table.appendChild(tr)
}
}
Access Student in a for in loop to get the keys.
for(var i = 0; i < collection.length; i++) {
var studentObjectSerialiseData = window.localStorage.getItem("student"+i)
var temp = JSON.parse(studentObjectSerialiseData)
console.log(temp);
for(var j in Student) {
console.log(temp[j]) ;
}
}

How I can find specific words in the string and add class (Javascript)

There is a text in P element. In this text you can select some terms with a mouse click. But I want to display some previously selected words in a different class
I want to find special words in this text and add class.
Related part
var previosSelectedWords = 'aute,dolor,ex,sed,velit'; // previos selected words
var PSW = previosSelectedWords.split(',');
for (var i = 0; i < words.length; i++) {
if (PSW[i] == words[i]) {
wrapped.push('<span class="previosSelecteds">' + words[i] + '</span>');
} else {
wrapped.push('<span>' + words[i] + '</span>');
}
}
But it doesn't show the pre-selected words. What could be the reason?
The problem was your loop: You used the same loop and the same index for both arrays.
// Loop through each word and wrap
for (var j = 0; j < PSW.length; j++) {
for (var i = 0; i < words.length; i++) {
if (PSW[j] == words[i]) {
var prevS = '<span class="previosSelecteds">' + words[i] + '</span>';
words[i] = prevS;
}
}
}
for (var i = 0; i < words.length; i++) {
if (!words[i].includes('previosSelecteds')) {
wrapped.push('<span>' + words[i] + '</span>');
}
else {
wrapped.push(words[i]);
}
}

How do I display an array inside a string in javascript?

This is the code :
list = ["Alex","John","Kit","Lenny"];
for(var i = 0; i < 4; i++) {
$("body").append("<p> list[i] </p>');
};
Look at the for loop(yes this is using jquery),i want to add the list items inside the paragraph headers.How do i do it ?
list[i] is not a string, it's a variable. To include it into the appended element, close the quotation marks in following way:
var list = ["Alex","John","Kit","Lenny"];
for(var i = 0; i < 4; i++) {
$("body").append("<p>" + list[i] + "</p>")
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Populating multidimensional array

The code below came as an included file with a beginner puzzle app tutorial I'm working through. The code works, however now that I've completed the tutorial, I'm trying to read through the files that came preloaded which were not explained.
I'm really tripped up over the "spacecount" variable, and what exactly it's doing. Can anyone comment each line in plain english, so that I can better understand how exactly the code below is populating the rowCount array. Thank you so much.
var totalRows = puzzle.length;
var totalCols = puzzle[0].length;
/* Loop through the rows to create the rowCount array
containing the totals for each row in the puzzle */
var rowCount = [];
for (var i = 0; i < totalRows; i++) {
rowCount[i]="";
spaceCount = 0;
for (var j = 0; j < totalCols; j++) {
if (puzzle[i][j] == "#") {
spaceCount++;
if (j == totalCols-1) rowCount[i] += spaceCount + " ";
} else {
if (spaceCount > 0) {
rowCount[i] += spaceCount + " ";
spaceCount = 0;
}
}
}
Here's a slightly more legible version:
var totalRows = puzzle.length;
var totalCols = puzzle[0].length;
/* Loop through the rows to create the rowCount array
containing the totals for each row in the puzzle */
var rowCount = [];
for (var i = 0; i < totalRows; i++) {
rowCount[i] = "";
spaceCount = 0;
for (var j = 0; j < totalCols; j++) {
if (puzzle[i][j] == "#") {
spaceCount++;
if (j == totalCols - 1) {
rowCount[i] += spaceCount + " ";
}
} else if (spaceCount > 0) {
rowCount[i] += spaceCount + " ";
spaceCount = 0;
}
}
}​
The confusing parts are probably the if blocks in the middle.
if (puzzle[i][j] == "#") { // If a puzzle piece is `#` (a space?)
spaceCount++; // Increment the spaceCount by 1.
if (j == totalCols - 1) { // Only if we are on the last column, add the text
// to the row.
rowCount[i] += spaceCount + " ";
}
} else if (spaceCount > 0) { // If the current piece isn't a `#` but
// spaces have already been counted,
// add them to the row's text and reset `spaceCount`
rowCount[i] += spaceCount + " ";
spaceCount = 0;
}​
From what I can tell, this code counts the number of consecutive pound signs and appends this text to each row.

Search and replace "-p"

how to search for exactly "-p" in the ids of huge html and append a counter after it i.e -p+counter. Please help.
If what you're asking is to replace -p with -pXX in all ids where XX is an increasing counter, you can do it like this:
var id, counter = 1;
var elems = document.getElementsByTagName("*");
for (var i = 0, len = elems.length; i < len; i++) {
id = elems[i].id;
if (id && id.indexOf("-p") != -1) {
elems[i].id = id.replace("-p", "-p" + counter++);
}
}
If you're just trying to add the text "+counter", then you can do it this way:
var id;
var elems = document.getElementsByTagName("*");
for (var i = 0, len = elems.length; i < len; i++) {
id = elems[i];
if (id && id.indexOf("-p") != -1) {
elems[i].id = id.replace("-p", "-p+counter");
}
}
If what you want (your original post is not very clear) is to replace only id values where the whole id is "-p", then you can use this:
var counter = 1;
var elems = document.getElementsByTagName("*");
for (var i = 0, len = elems.length; i < len; i++) {
if (elems[i].id == "-p") {
elems[i].id += counter++);
}
}
OK, fourth guess at what you want (based on your comments) if you want -p replaced only if the p isn't followed by another letter:
var id, counter = 1;
var elems = document.getElementsByTagName("*");
for (var i = 0, len = elems.length; i < len; i++) {
id = elems[i].id;
if (id) {
elems[i].id = id.replace(/\-p([\W_]|$)/, "-p" + counter++ + "$1");
}
}
And, here's a demo: http://jsfiddle.net/jfriend00/Ug7VN/
A jQuery version of this last one would work like this:
var counter = 1;
$('[id]').each(function() {
this.id = this.id.replace(/\-p([\W_]|$)/, "-p" + counter++ + "$1");
});
With jQuery, this should be as simple as:
var counter = 0;
$('[id*="-p"]').each(function() {
$(this).attr('id', $(this).attr(id).replace('-p', '-p' + counter++));
});
Edit: if you only want items with an id ending in -p, you can use the following (note the different selector):
var counter = 0;
$('[id$="-p"]').each(function() {
$(this).attr('id', $(this).attr(id).replace(/-p$/, '-p' + counter++));
});

Categories

Resources