I'm receiving an error of read-only in this script that I'm trying to run.
I'm trying to learn const and the new es6 and I have to admit that it is pretty straightforward but in this case, I'm not 100% sure that that's the problem.
Here's my code:
$(() => {
const containerImage = document.querySelector( '.images' );
const getPictures = () => {
$.ajax({url: "https:myurl/photos.json", success: function(result) {
const singleImage = result.photos;
const content = "";
content += "<div class='row'>";
for(let i = 0; i < singleImage.length; i++){
content.innerHTML += `<div class="col-md-4">
<img src=${singleImage[i].image}>
</div>`;
};
content += "</div>";
containerImage.innerHTML = content;
}});
}
getPictures();
});
Does anyone notice any strange thing in my code?
Plus the console mention and throw this error:
function _readOnlyError(name) { throw new Error("\"" + name + "\" is read-only"); }
But I'm not even in the strict mode.
Consts can't be modified. Change:
const content = "";
content += "<div class='row'>";
to
let content = "";
content += "<div class='row'>";
Related
Hello everyone I am a junior web dev. and I've been stuck on this task for weeks now :[]. I need an input field that will show default text coming from the backend. Restrictions I need for this input field are: The input line should break after reaching 30 characters and some parts of default text should be noneditable.
//Here's the closest solution that I came up
import React, { useEffect } from "react";
import styles from "./TextEditor.module.css";
const TextEditor = (props) => {
var limit = 80000; //height limit
let defaultvalueArr = props.data.variables.map((vari, index) => {
return vari.texts.map((p, index) => {
return p;
});
});
useEffect(() => {
const box = document.getElementById(props.title);
var charlimit = 30; // char limit per line
var space;
box.onkeyup = function () {
var lines = box.value.split("\n");
console.log(box.value, "box.value");
for (var i = 0; i < lines.length; i++) {
if (lines[i].length <= charlimit) continue;
var j = 0;
space = charlimit;
while (j++ <= charlimit) {
if (lines[i].charAt(j) === " ") space = j;
}
lines[i + 1] = lines[i].substring(space + 1) + (lines[i + 1] || "");
lines[i] = lines[i].substring(0, space);
}
box.value = lines.slice(0, 500).join("\n");
};
box.oninput = function() {
box.style.height = "";
box.style.height = Math.min(box.scrollHeight, limit) + "px";
};
box.value = defaultvalueArr.join("\n");
}, []);
return (
<div className={styles.TextEditor}>
<textarea
id={props.title}
className={styles.TextArea}
// rows={defaultvalueArr[0].length}
></textarea>
</div>
);
};
export default TextEditor;
output
the problem with this solution is that when the number of characters reaches 30 the cursor jumps at the end of text
I have a simple csv file. Sample data is given below (sample.csv).
date,team_1,team_2
2019-06-12,AUS,PAK
2019-06-13,IND,NZ
I want the above to be displayed as a table in a HTML page, such that new rows will automatically add to the table as and when a new record is added to the csv file.
Can someone please help me with a very simple solution?
EDIT: Based on answer to this question, I have written (copied) the following piece of code, but other than the first line, it does not show anything.
function createTable() {
var array = [
["date","team_1","team_2"],
["2019-06-12","AUS","PAK"],
["2019-06-13","IND","NZ"]
];
var content = "";
array.forEach(function(row) {
content += "<tr>";
row.forEach(function(cell) {
content += "<td>" + cell + "</td>";
});
content += "</tr>";
});
document.getElementById("t1").innerHTML = content;
}
createTable()
<table id="t1"> </table>
Here this code works correctly. Open a file.csv as you described. When you add or delete line in the CSV it works accordingly in the HTML page.
var init;
const logFileText = async file => {
const response = await fetch(file);
const text = await response.text();
all = text.split('\n');
if (init !== all.length) {
//console.log(all.length, init);
init = all.length;
//console.log('changed');
var arr=[];
all.forEach(el => {
el=el.split(',');
arr.push(el);
});
// console.log(arr);
createTable(arr);
}
}
function createTable(array) {
var content = "";
array.forEach(function (row) {
content += "<tr>";
row.forEach(function (cell) {
content += "<td>" + cell + "</td>";
});
content += "</tr>";
});
document.getElementById("t1").innerHTML = content;
}
var file = 'file.csv';
logFileText(file);
setInterval(async () => {
await logFileText(file);
}, 2000);
<table id="t1"> </table>
var pageCounter = 1;
var animalContainer = document.getElementById("animal-info");
var btn = document.getElementById("btn");
btn.addEventListener("click", function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json');
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var ourData = ourRequest.responseText;
renderHTML(ourData);
} else {
console.log("We connected to the server, but it returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
pageCounter++;
if (pageCounter > 3) {
btn.classList.add("hide-me");
}
});
function renderHTML(data) {
var htmlString = "";
for (i = 0; i < data.length; i++) {
htmlString += "<p>" + data[i].name + " is a " + data[i].species + "</p>";
}
animalContainer.insertAdjacentHTML('beforeend', htmlString);
}
I have checked every thing and i don't know what is wrong with the code... I am trying to load information on the fly using Json and ajax
You did not parse your data to JSON so what you have to do is parse your "ourData" to JSON.. Remove and add this line of to your code.
var ourData = JSON.parse(ourRequest.responseText);
I am trying to get the div elements to be dynamically created and their values updated every second using the code:
setInterval(function() {
google.script.run.withSuccesshandler(function(data) {
var out = '';
$(data).each(function() {
out += "<p>" + $(this).val() + "</p>";
});
$('#item1').html(out);
}).getReadyLine();
}, 1000);
<div class="col-sm-3 col1">
<h1 id="readyLine">Ready Line, <?= getCountReadyLine() ?> items</h1>
<div class="item1" id="item1">
</div>
</div>
Code.gs code:
function getReadyLine() {
var rawData = sheetMAT.getRange(3, 2, sheetMAT.getLastRow() - 2, 5).getValues();
for (var i=0; i<rawData.length; i++) {
if (rawData[i][3] === "A Ready Line" && rawData[i][4] === "ATY") {
temp1 = ' ' + data[i][0];
temp2.push(data[i][1], temp1);
dataReadyLine.push(temp2);
temp1 = '';
temp2 = [];
}
}
return dataReadyLine;
}
But it is giving the following error in the Console:
VM4084 userCodeAppPanel:67 Uncaught TypeError: google.script.run.withSuccesshandler is not a function
at VM4084 userCodeAppPanel:67
(anonymous) # VM4084 userCodeAppPanel:67
Why is it not recognized as a function? Is there any mistake in the code i am missing?
The correct syntax is
google.script.run.withSuccessHandler()
Please note 'H' in Handler is capital
I created a test server that sends chunks of stringified JSON. When I connect to the server it sends invalid JSON and for the life of me I can't figure out why. The output adds an extra double quotation mark.
Server code:
const net = require('net'),
server = net.createServer(function(connection) {
console.log('subscriber connected.');
// send first chunk immediately
connection.write('{"type":"changed","file":"targ"');
let timer = setTimeout(function() {
connection.write('et.txt","timestamp":1358175758495}' + '\n');
connection.end();
}, 1000);
connection.on('end', function() {
clearTimeout(timer);
console.log('subscriber disconnected');
});
});
server.listen(5432, function() {
console.log('test server listening for subs...')
});
ldj.js
'use strict';
const
events = require('events'),
util = require('util'),
// client constructor
LDJClient = function(stream) {
events.EventEmitter.call(this);
let self = this;
let buffer = '';
stream.on('data', function(data) {
buffer += data;
console.log(buffer)
let boundary = buffer.indexOf('\n');
while(boundary !== -1) {
let input = buffer.substr(0, boundary);
buffer = buffer.substr(boundary + 1);
//self.emit('message', JSON.parse(input));
boundary = buffer.indexOf('\n');
}
});
};
util.inherits(LDJClient, events.EventEmitter);
// expose module methods
exports.LDJClient = LDJClient;
exports.connect = function(stream) {
return new LDJClient(stream);
};
Output:
{"type":"changed","file":"targ"
{"type":"changed","file":"targ"et.txt","timestamp":1358175758495}
That extra " should not be in "target.txt" value. Any ideas?
TIA
rathern than splitting string manualy try to get whole string and split it to chunks and then send it:
var data = '{"type":"changed","file":"target.txt","timestamp":1358175758495}';
var chunks = data.match(/.{1,10}/g); // 10 symbol chunks
for(var i = 0; i < chunks.length; i++) {
var chunk = chunks[i];
setTimeout(function() {
if(connection) {
connection.write(chunk+'\n');
if(i + 1 == chunks.length) {
connection.end();
}
}
}, i*1000);
}
connection.on('end', function() {
console.log('subscriber disconnected');
});