JS- textarea lines to javascript array - javascript

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]);
}
}

Related

Create dynamic buttons with jQuery

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..

Show array from apps script file in html file

I have an array of email drafts that I got in apps script. I want to show them in a html file in a select element, but it shows up blank when I run it. Code below
code.gs
function doGet(e) {
return HtmlService.createHtmlOutput("index");
}
function doSomething() {
var drafts = GmailApp.getDrafts();
var drafty = [];
for(var i = 0; i < drafts.length; i++){
drafty.push(drafts[i].getMessage().getSubject());
}
Logger.log(drafty);
return drafty;
var select = document.getElementById("select"),
arr = drafty;
for(var i = 0; i < arr.length; i++)
{
var option = document.createElement("OPTION"),
txt = document.createTextNode(arr[i]);
option.setAttribute("value", arr[i]);
option.appendChild(txt);
document.getElementById("select").appendChild(option);
}
index.html
<!DOCTYPE html>
<html>
<head>
<script>
google.script.run.doSomething();
</script>
</head>
<body>
<select id="select" class="addon-select addon-form-input"></select>
</body>
Something like this:
gs:
function doSomething() {
var drafts=GmailApp.getDrafts();
var drafty=[];
for(var i=0;i<drafts.length;i++){
drafty.push(drafts[i].getMessage().getSubject());
}
Logger.log(drafty);
return drafty;
}
html:
<!DOCTYPE html>
<html>
<head>
<script>
google.script.run
.withSuccessHandler(function(A){
var id='select';
var select = document.getElementById(id);
select.options.length = 0;
for(var i=0;i<A.length;i++) {
select.options[i] = new Option(A[i],A[i]);
}
})
.doSomething();
</script>
</head>
<body>
<select id="select"></select>
</body>
</html>

How to put the elements of array of arrays in table cells?

<html>
<head>
<title>Array of Arrays</title>
<script type="text/javascript">
function matrix()
{
var e=prompt("Cols?",0);
var f=prompt("Rows?",0);
var matrix = new Array();
for (var i=0;i<e;i++)
{
matrix[i] = new Array();
for (var j=0;j<f;j++)
{
matrix[i][j]=Math.floor((Math.random()*1000)+1);
}
}
for (var i=0; i<=e-1; i++)
{
document.getElementById("keret").innerHTML=
document.getElementById("keret").innerHTML+"<tr>";
for (var j=0; j<=f-1; j++)
{
document.getElementById("keret").innerHTML=
document.getElementById("keret").innerHTML+"<td>"+matrix[i][j]+"</td>";
}
document.getElementById("keret").innerHTML=
document.getElementById("keret").innerHTML+"</tr>";
}
document.getElementById("keret").innerHTML=
document.getElementById("keret").innerHTML+"</table>";
}
</script>
</head>
<body onload="matrix()">
<table border="1" id="keret">
</body>
</html>
This script makes a user defined array of arrays, and filling it up with random numbers. My problem is:
I can't make the script to put the values in dividual cells.
Your second loop can be as follows:
for (var i = 0; i < e; i++) {
var row = document.createElement("tr");
for (var j = 0; j < f; j++) {
var cell = document.createElement("td");
cell.innerHTML = matrix[i][j];
row.appendChild(cell);
}
document.getElementById("keret").appendChild(row);
}
This appends a tr element for each row and a td element for each column within the row. Then it appends the row to your table. Your HTML would be slightly modified as well:
<table border="1" id="keret"></table>
(Rows & Columns prompts need to be switched but I didn't want to mess up your variable names).
Fiddle: http://jsfiddle.net/verashn/7Rwnc/
<html>
<head>
<title>Array of Arrays</title>
<script type="text/javascript">
function matrix() {
var e = prompt("Cols?",0),
f = prompt("Rows?",0),
allRows = [],
row = [];
for (var i = 0; i < e; i += 1) {
row = ['<tr>', '</tr>']; // this serves as your initial template
for (var j = 0; j < f; j += 1) {
// now create the columns
row.splice(-1, 0, '<td>' + Math.floor((Math.random()*1000)+1) + '</td>')
}
allRows.push(row.join(''));
}
document.getElementById("keret").innerHTML = allRows.join('');
}
</script>
</head>
<body onload="matrix()">
<table border="1" id="keret"></table>
</body>
</html>

Select Nodes & Sum values

Question
How do you select text node values identified with a specific attribute (background color #00FF00)?
As I'm new to javascript, I'm not sure how to do the first step:
use the js dom to select the node with 00FF00
split the string with " " as the separator
loop through and add each split[2] with +=
write the sum (240+80+600) to html
Code
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function() {
var data = document.getElementsByTagName('span');
document.write(data);
};
</script>
</head>
<body>
<div class="box">
<span class="highlight">Dave collected 700 items.</span>
</div>
<div class="box">
<span class="highlight" style="background-color:#00FF00;">Bob collected 240 items.</span>
</div>
<div class="box">
<span class="highlight" style="background-color:#00FF00;">Bob collected 80 items.</span>
</div>
<div class="box">
<span class="highlight" style="background-color:#00FF00;">Bob collected 600 items.</span>
</div>
</body>
</html>
var els = document.querySelectorAll('span.highlight');
var len = els.length;
//console.log(len); //returns 4
var total = 0;
for (var i=0; i < len; i++) {
if (els[i].style.backgroundColor.toLowerCase() === 'rgb(0, 255, 0)') {
var txt = els[i].innerHTML;
//split txt into array
split = txt.split(" ");
total += parseInt(split[2]);
}
}
console.log(total);
Unless you are trying to scrape the content of another site and have no control over the HTML structure, I would recommend adding an additionnal class or an attribute to these that would ease the selection of these nodes.
However, you could do it like:
var els = document.querySelectorAll('span.highlight'),
i = 0,
len = els.length;
for (; i < len; i++) {
if (els[i].style.backgroundColor.toLowerCase() === '#00ff00') {
//code
}
}
As previously mentioned, it's probably best to use a class definition. But if you must select by color, the following code should do it for you.
var data = document.getElementsByTagName('span');
var len = data.length;
for(var i = 0; i < len; ++i){
var styles = data[i].getAttribute('style');
if(styles.indexOf('background-color:#00FF00') != -1){
//Do something
}
}

call external .js file in html

I have an array.js file and an index.html.
My array.js file looks like this:
function go(){
var array = new Array();
array[0] = "Red";
array[1] = "Blue";
array[3] = "Green";
for (var i=0; i < array.length; i++){
document.write("<li>" + array[i] + "<br />");
}
}
My index.html file looks like this:
<html>
<head>
<script type="text/javascript" src="array.js"></script>
</head>
<body>
<input type="button" onclick="go()" value="Display JS Array"/>
<script>
go();
</script>
</body>
</html>
When I click the Display JS Array button on the HTML page, nothing happens.
I want the array elements to be displayed after I click the button.
It should look like:
Red
Blue
Green
You can change the function by taking the parent element of li elements as parameter.
function go(element){
var array = new Array();
array[0] = "Red";
array[1] = "Blue";
array[3] = "Green";
var ul = document.createElement("ul");
for (var i=0; i < array.length; i++) {
var li = document.createElement("li");
li.innerHtml = array[i];
ul.appendChild(li);
}
body.insertAfter(ul, element);
}
<input type="button" onclick="go(this)" value="Display JS Array"/>
replace this document.write("<li>" + array[i] + "<br />"); with document.write("<li>" + array[i] + "</li>");
and in your HTML file, remove
<script>
go();
</script>
because already you calling go(); function on onclick. and in your array, array[2] will give undefined.
try this its working for me :
<html>
<head>
<script type="text/javascript">
function go(){
var array = new Array();
array[0] = "Red";
array[1] = "Blue";
array[2] = "Green";
li = document.getElementById("list");
li_arr = "";
for (var i=0; i < array.length; i++){
li_arr += "<li>" + array[i] + "</li>";
}
li.innerHTML = li_arr;
}
</script>
</head>
<body>
<input type="button" onclick="go()" value="Display JS Array"/>
<ul id="list"></ul>
</body>
</html>
​
Your code is quite ok. And working fine. Yes you can use external JS or internal JS .
By using External JS: -
Test.html
<html>
<head>
<script type="text/javascript" src="arrayy.js"></script>
</head>
<body>
<input type="button" onclick="go()" value="Display JS Array"/>
</body>
</html>
arrayy.js
function go(){
var array = new Array();
array[0] = "Red";
array[1] = "Blue";
array[3] = "Green";
for (var i=0; i < array.length; i++){
document.write("<li>" + array[i] + "<br />");
}
}
These above codes are running in Mozilla Firefox ,IE 8 and some other browser.
By Using Internal JS: -
<html>
<head>
<script>
function go(){
var array = new Array();
array[0] = "Red";
array[1] = "Blue";
array[3] = "Green";
for (var i=0; i < array.length; i++){
document.write("<li>" + array[i] + "<br />");
}
}
</script>
</head>
<body>
<input type="button" onclick="go()" value="Display JS Array"/>
</body>
</html>
It works just fine for me.
But as shreedhar said:
You need to delete
<script>
go();
</script>
this otherwise it will be displayed before you pressed the button.
An since array[2] is undefined you need to filter that one from your array.
Suppose if you are using jquery dom ready function then make the modification on arrayy.js like this.
$(document).ready(function() {
this.go = function(){
var array = new Array();
array[0] = "Red";
array[1] = "Blue";
array[3] = "Green";
for (var i=0; i < array.length; i++){
document.write("<li>" + array[i] + "<br />");
}
}
}

Categories

Resources