Create dynamic buttons with jQuery - javascript

I'm attempting to dynamically create buttons with text loaded from a file into an array. The text loads, the array's created, but no buttons. I realize this has been asked before, but I must be doing something wrong.
var database = [];
var total;
document.getElementById('file').onchange = function() {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent) {
var lines = this.result.split('\n');
for (var line = 0; line < lines.length; line++) {
database[line] = lines[line].trim();
}
total = line;
};
reader.readAsText(file);
};
/*
function mkbuttons() {
for (let i = 0; i < total; i++)
$(document).ready(function() {
for (i = 0; i < total; i++) {
console.log(database[i]);
$('<button/>', {
text: database[i],
id: 'btn_' + i,
click: function() {
alert('hi');
}
});
}
});
}
*/
function mkbuttons() {
$(document).ready(function() {
for (i = 0; i < total; i++) {
console.log(database[i]);
$('<button/>', {
text: database[i],
id: 'btn_' + i,
click: function() {
alert('hi');
}
});
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Create Buttons</title>
</head>
<body>
<input type="file" name="file" id="file" accept=".txt">
<br><br>
<button i onclick="mkbuttons()">Make Buttons</button>
</body>
</html>

How do you think of this solution?
var database = [];
var total;
document.getElementById('file').onchange = function() {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent) {
var lines = this.result.split('\n');
for (var line = 0; line < lines.length; line++) {
database[line] = lines[line].trim();
}
total = line;
};
reader.readAsText(file);
};
function mkbuttons() {
for (let i = 0; i < total; i++)
$(document).ready(function() {
for (i = 0; i < total; i++) {
console.log(database[i]);
var newBtn = $('<button/>', {
text: database[i],
id: 'btn_' + i,
click: function() {
alert('hi');
}
});
$('#buttons').append(newBtn);
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Create Buttons</title>
</head>
<body>
<input type="file" name="file" id="file" accept=".txt">
<br><br>
<button i onclick="mkbuttons()">Make Buttons</button>
<div id="buttons">
</div>
</body>
</html>

There are two glaring issues with your for loop:
Only use $(document).ready outside the function and only once. It should not be inside a for loop
You have an inner loop which is also using the same index variable name of i
Once you fix this syntax things should work better, or at least be easier to debug..

Related

Convert excel to json but with only one header

I am trying to write an html with JS program that will convert an excel file into json which is does bit it does not format it the way I need to. So basically it spits out when finished
[
{
"imei": "357271093291264"
},
{
"imei": "353094106032150"
},
{
"imei": "353112106434588"
}
]
but what I need is.
[
{
"imei": "357271093291264", "353094106032150", "353112106434588"
}
]
So it is taking imei from cell A1 and using it over and over. I just need it
to keep adding on as I go down the rows.
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://unpkg.com/read-excel-file#4.x/bundle/read-excel-file.min.js"></script>
</head>
<body>
<div style="margin: auto;width: 50;margin-top: 80px;padding: 30px;background-color: #dedede;">
<h2>Excel to JSON Converter</h2>
<input type="file" id="input" />
<br> <br>
<textarea name="json-data" id="json-data" rows="25" style="width: 100%;"></textarea>
<br><br>
<button id="dl-json">Download JSON File</button>
</div>
<script>
var input = document.getElementById('input');
input.addEventListener('change', function(){
readXlsxFile(input.files[0]).then(function(data){
var i = 0;
var headers = [];
var json_object = [];
data.map((row, index)=> {
if (i == 0){
headers = row;
}
if (i > 0){
var temp = {};
for (var x = 0; x < row.length; x++){
temp[headers[x]] = row[x];
}
json_object.push(temp);
}
i++;
});
document.getElementById('json-data').value = JSON.stringify(json_object, null, 2)
});
document.getElementById('dl-json').onclick = function() {
var json_str = document.getElementById('json-data').value;
downloadObjectAsJson(json_str, '');
}
function downloadObjectAsJson(str, filename){
var data_str = "data:text/json;charset=utf-8," + encodeURIComponent(str);
var anchor = document.createElement('a');
anchor.setAttribute("href", data_str);
anchor.setAttribute("download", filename + ".json");
}
});
</script>
</body>
</html>
I have tried playing around with it and pulling out certain parts and setting different variables to certain values.
The shape of your output doesn't seem to make sense. Do you want the first element in your output array to be a key:value pair such as "headerText":"row2Value", and then the rest just strings?
If so, this should work for you:
var input = document.getElementById("input");
input.addEventListener("change", function () {
readXlsxFile(input.files[0]).then(function (data) {
let exportData = [];
for (i = 1; i < data.length; i++) {
i === 1
? exportData.push({ imei: data[i].toString() })
: exportData.push(data[i].toString());
}
document.getElementById("json-data").value = JSON.stringify(exportData);
});
document.getElementById("dl-json").onclick = function () {
var json_str = document.getElementById("json-data").value;
downloadObjectAsJson(json_str, "");
};
function downloadObjectAsJson(str, filename) {
var data_str =
"data:text/json;charset=utf-8," + encodeURIComponent(str);
var anchor = document.createElement("a");
anchor.setAttribute("href", data_str);
anchor.setAttribute("download", filename + ".json");
}
});
If you only need the key, then an array of values, this will work better for you:
readXlsxFile(input.files[0]).then(function (data) {
let exportData = [];
for (i = 1; i < data.length; i++) {
exportData.push(data[i].toString());
}
document.getElementById("json-data").value = JSON.stringify({
imei: exportData,
});
});

HtmlService: google.script.run not recognizing gs function

I'm currently trying to pass an array of values from a Google Sheet to the HtmlService where I will have the user choose an option and eventually pass it back to the .gs script. I have been using these two links as references:
1. Google Documentation
2. Stack Overflow example
When running the code, I looked at my console and noticed this error:
VM3051:4 Uncaught TypeError: google.script.run.withSuccessHandler(...).getVersionArray is not a function
It appears that getVersionArray() is not being passed correctly. When removing this function from the rest of that google.script.run call, the error goes away.
Also, per link two, I tried that code with the template and never even got a window to pop up, so I have been using the HtmlOutput example from the Google documentation link as a starting point. I have also tried the code with and without the SandboxMode declaration.
gs code:
function bugPieChart() {
getVersionArray();
openDialog();
function getVersionArray() {
var ss = SpreadsheetApp.getActive();
var valuesR = ss.getSheetByName("report").getRange('R1:R').getValues();
var valuesS = ss.getSheetByName("report").getRange('S1:S').getValues();
var versionRSArray = [];
for (var i = 0; i < valuesR.length; i++) {
versionRSArray.push(valuesR[i][0]);
}
for (var i = 0; i < valuesS.length; i++) {
versionRSArray.push(valuesS[i][0]);
}
versionRSArray.sort();
var uniqueArray = [];
uniqueArray.push(versionRSArray[0]);
for (var i in versionRSArray ) {
if((uniqueArray[uniqueArray.length-1]!=versionRSArray[i]) && (versionRSArray[i] !== "")) {
uniqueArray.push(versionRSArray[i]);
}
}
return uniqueArray;
}
function openDialog() {
var html = HtmlService.createHtmlOutputFromFile('index');
SpreadsheetApp.getUi().showModalDialog(html, 'Dialog title');
var htmlOutput = html.setSandboxMode(HtmlService.SandboxMode.NATIVE);
return htmlOutput;
}
}
index.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(function() {
google.script.run.withSuccessHandler(buildOptionsList)
.getVersionArray();
});
function buildOptionsList(uniqueArray) {
var list = $('#optionList');
list.empty();
for (var i = 0; i < uniqueArray.length; i++) {
list.append('<option value="' + uniqueArray[i].toLowerCase() + '">' + uniqueArray[i] + '</option>');
}
}
</script>
</head>
<body>
<select id="optionList">
<option>Loading...</option>
</select>
<input type="button" value="Close" onclick="google.script.host.close()" />
</body>
</html>
I think your just missing a closing bracket on the function above it.
function bugPieChart() {
getVersionArray();
openDialog();
}
function getVersionArray() {
var ss = SpreadsheetApp.getActive();
var valuesR = ss.getSheetByName("report").getRange('R1:R').getValues();
var valuesS = ss.getSheetByName("report").getRange('S1:S').getValues();
var versionRSArray = [];
for (var i = 0; i < valuesR.length; i++) {
versionRSArray.push(valuesR[i][0]);
}
for (var i = 0; i < valuesS.length; i++) {
versionRSArray.push(valuesS[i][0]);
}
versionRSArray.sort();
var uniqueArray = [];
uniqueArray.push(versionRSArray[0]);
for (var i in versionRSArray ) {
if((uniqueArray[uniqueArray.length-1]!=versionRSArray[i]) && (versionRSArray[i] !== "")) {
uniqueArray.push(versionRSArray[i]);
}
}
return uniqueArray;
}
function openDialog() {
var html = HtmlService.createHtmlOutputFromFile('index');
SpreadsheetApp.getUi().showModalDialog(html, 'Dialog title');
var htmlOutput = html.setSandboxMode(HtmlService.SandboxMode.NATIVE);
return htmlOutput;
}

using js to parse log and filter out something

I am quite new in javascript and I am trying to parse the log and filter out something. The log looks like:
v=5,ci=3,si=60,sv=1,ss=active,es=-,ai=a23-369b-4da3-b2da-630aee75f8c5,ip='99.114.107.39',rm=GET,rv=HTTP/1.1,rs=200,rt=0.787020,rr='/tag/febe1eab436e98eb4ed3711870496c91/st.js?l=http%3A%2F%2Fwww.michaels.com%2Fv
The output should be printed by splitting on ,, line by line and also filter out something that I don't need. e.g, I only need ip and rr attributes, so the output should look like:
ip='99.114.107.39'
rr='/tag/febe1eab436e98eb4ed3711870496c91/st.js?l=http%3A%2F%2Fwww.michaels.com%2Fv
The code I have is following, but it doesn't work:
<!doctype html>
<html>
<head>
<title>reading file</title>
<script>
function readText(obj){
var file = obj.files[0],
div=document.getElementById('main');
if(file){
div.innerHTML='';
var reader = new FileReader();
reader.onerror = function(event){
div.innerHTML='The file can\'t be read! Error ' + event.target.error.code;
}
reader.onload = function(event){
var cont = event.target.result.split(',');
for(var i=0; i<cont.length; i++){
var name = cont.split('=');
if (name[0]==="rr") {
div.innerHTML+=cont[i]+'<br />';
}
}
}
reader.readAsText(file);
}
}
window.onload=function(){
document.getElementById('ff').onchange=function(){readText(this);}
}
</script>
</head>
<body>
<input type="file" id="ff" />
<div id="main"></div>
</body>
</html>
Use javascript's split():
DEMO
Example:
window.onload = function () {
var text = "v=5,ci=3,si=60,sv=1,ss=active,es=-,ai=a23-369b-4da3-b2da-630aee75f8c5,ip='99.114.107.39',rm=GET,rv=HTTP/1.1,rs=200,rt=0.787020,rr='/tag/febe1eab436e98eb4ed3711870496c91/st.js?l=http%3A%2F%2Fwww.michaels.com%2Fv";
var ip = '',
rr = '';
var splits = text.split(',');
for (var i = 0; i < splits.length; i++) {
if (splits[i].indexOf('ip') > -1)
ip = splits[i];
else if (splits[i].indexOf('rr') > -1)
rr = splits[i];
}
document.getElementById('divIp').innerHTML = ip;
document.getElementById('divRr').innerHTML = rr;
};

JS- textarea lines to javascript array

I want save textarea lines in js array.
this code works but if we have empty line in textarea, array elements values set undefined after empty line!
DEMO: http://jsfiddle.net/pYTjR/3/
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function check(){
var lines = $('#links').val().split(/\n/);
var texts = []
for (var i=0; i < lines.length; i++) {
if (/\S/.test(lines[i])) {
texts.push($.trim(lines[i]));
}
var links = texts;
var str = links[i];
alert(i+"- "+str);
}
}
</script>
</head>
<body>
<textarea id="links" name="upload" cols=80 rows=10>
www.example.com/book111.pdf
www.example.com/book222.pdf
www.example.com/book333.pdf
www.example.com/book444.pdf
www.example.com/book555.pdf
</textarea>
<input type="submit" id="getsize" name="getsize" value="textarea to array" onclick= "check()" />
</body>
</html>
DEMO: http://jsfiddle.net/pYTjR/3/
I think it is functioning as you are expecting except not alerting correctly. Try this:
http://jsfiddle.net/pYTjR/7/
function check(){
var lines = $('#links').val().split(/\n/);
var texts = [];
for (var i=0; i < lines.length; i++) {
if (/\S/.test(lines[i])) {
texts.push($.trim(lines[i]));
}
}
for (var i=0; i < texts.length; i++) {
alert(i+"- "+texts[i]);
}
}

Shade Color of Dropdown and Select on focus/onblur

How can the code below be modified such that it will apply the onblur and onfocus to the text boxes and select boxes? Right now it only works with text boxes, and I can't seem to get it to apply to the select boxes.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
window.onload =
function fnOnLoad() {
var t = document.getElementsByTagName('INPUT');
var i;
for(i=0;i<t.length;i++)
{
//alert(t[i].type)
if(t[i].type == "text")
{
t[i].attachEvent('onfocus', new Function("fnTXTFocus('"+t[i].id+ "')"));
t[i].attachEvent('onblur', new Function("fnTXTLostFocus('"+t[i].id+ "')"));
}
}
}
function fnTXTFocus(varname) {
var objTXT = document.getElementById(varname)
objTXT.style.backgroundColor = "#FFFF80";
}
function fnTXTLostFocus(varname)
{
var objTXT = document.getElementById(varname)
objTXT.style.backgroundColor = "#FFFFFF";
}
</script>
</head>
<body>
<input id="t1" type="text" >
<input id="t2" type="text" >
<input id="t3" type="text" >
<br><br>
<select size="d1" ></select>
<select size="d2" ></select>
<select size="d3" ></select>
<p>When the input field gets focus,
a function is triggered which changes the background-color.</p>
</body>
</html>
So what you need to do is also get all selects and attach the event handlers to them:
var s = document.getElementsByTagName('SELECT');
Try this:
function fnOnLoad() {
var inputs = document.getElementsByTagName('INPUT');
for(var i = 0; i < inputs.length; i++)
{
inputs[i].attachEvent('onfocus', function(){
this.style.backgroundColor = "#FFFF80";
});
inputs[i].attachEvent('onblur', function(){
this.style.backgroundColor = "#FFFFFF";
});
}
var selects = document.getElementsByTagName('SELECT');
for(var i = 0; i < selects.length; i++)
{
selects[i].attachEvent('onfocus', function(){
this.style.backgroundColor = "#FFFF80";
});
selects[i].attachEvent('onblur', function(){
this.style.backgroundColor = "#FFFFFF";
});
}
}
window.onload = fnOnLoad;
<script type="text/javascript">
function fnOnLoad() {
var t = document.getElementsByTagName('INPUT');
for (var i = 0; i < t.length; i++) {
t[i].onfocus = function() { this.style.backgroundColor = '#FFFFC4';};
t[i].onblur = function() { this.style.backgroundColor = '#FFFFFF'; };
}
var d = document.getElementsByTagName('SELECT');
for (var i = 0; i < d.length; i++) {
d[i].onfocus = function() { this.style.backgroundColor = '#FFFFC4'; };
d[i].onblur = function() { this.style.backgroundColor = '#FFFFFF'; };
}
}
</script>

Categories

Resources