How to Load an Array from a text file in JavaScript? - javascript

I am a complete Beginner using Javascripts and simple descriptive solutions would be very helpful. This is completely on one machine, no server available and I just need to do basic stuff using HTML etc.
I have a task wherein I need to provide an option on the browser to Upload a text file (containing numbers separated by a comma) using Mozilla Firefox only, read the uploaded file into an array, perform some computation on that array and then store the array in another text file and provide an option on the web browser to download the output file.
This is what I have done so far.
**********************************
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<script src="javaScripts/script.js" type="text/javascript"></script>
<script src="script.js"></script>
<head runat="server">
<title></title>
</head>
<body>
<input type="file" name="input" size="40"/>
<br />
<input id="Button" type="button" value="Average" onclick="CPU_Average()"/>
<br />
<span id="output1"></span>
</body>
</html>
<script id="average" type="text/javascript">
function CPU_Average() {
var output1 = document.getElementById("output1");
output1.innerHTML = "";
var row = 5;
var col = 5;
var size = row*col;
try{
var windowSize = 3;
var i=0,j=0,k=0,p=0,q=0,count=0,limit=1;
var check=0;
var sum=0.0;
var vec1 = new Uint32Array(size);
var vec_op = new Float32Array(size);
for (i=0; i<size; i=i+1) {
vec1[i] = Math.floor(Math.random() * 100); //Random number 0..99
}
output1.innerHTML += "<br>Vector length = " + size;
output1.innerHTML += "<br>Vector1 = ";
for (i = 0; i < size; i = i + 1) {
output1.innerHTML += vec1[i] + ", ";
}
for(k=0;k<size;k=k+1)
{
sum=0.0;
i=Math.floor(k/row);
j=k%row;
count=0;
for(p=i-limit;p<=i+limit;p=p+1)
{
for(q=j-limit;q<=j+limit;q=q+1)
{
if(p>=0 && q>=0)
{
check = ((p*row)+q);
if(check<size && ((q*col)+p)<size)
{
sum = sum+vec1[check];
count=count+1;
}
}
}
}
vec_op[k] = (sum/count);
}
output1.innerHTML += "<br>Result = ";
for (i = 0; i < size; i = i + 1) {
output1.innerHTML += vec_op[i].toFixed(2) + ", ";
}
}
catch(e) {
document.getElementById("output1").innerHTML
+= "<h3>ERROR:</h3><pre style=\"color:red;\">" + e.message + "</pre>";
throw e;
}
}
</script>
***********************
currently I am generating random numbers and storing them in the input array(vec1), but I need to load that array from an input file. Also my output array(vec_op) prints into a text box but I need to write that array in a text file, each element separated by a comma and allow the user to download it.
If I need to use JQuery or Ajax for it then please explain how to add them in the above code.
Thanks.

Related

How to get the proper Javascript output for the number pyramid

I am currently working on a 1/2 pyramid of numbers. I can get the output to total up the line and get everything but the * sign between the numbers. Hoping that someone out there can lend a helping hand. Here is the code that I have completed.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Assignment 1</title>
<script>
var num = "";
var match ="";
var size = prompt("Enter the size of the pyramid");
if (size >=1) {
var total="1";
for(var i=1; i<=size; i++)
{
if (i < size){
num = num + i + " "
} if (i==size) {
num =num + i }
total= total * i;
document.write(num + " = "+ total + "<br>");
}
}else {
alert("Please enter a number equal to or greater than 1");
}
var total="1";
</script>
</head>
<body>
<main>
<!-- Will show after the script has run -->
<h1>Assignment 1</h1>
</main>
</body>
</html>
-
I am looking for output like this
1=1
1*2=2
1*2*3=6
1*2*3*4=24
1*2*3*4*5=120
and so on.
Thanks again
You can use a loop like this and make the total time the new iteration value:
var total = 1;
var newList = [];
for(let i=1; i<=5; i++) {
newList.push(i);
total *= i;
console.log(newList.join('*') + '=' + total)
}
Run code snippet output:
1=1
1*2=2
1*2*3=6
1*2*3*4=24
1*2*3*4*5=120

Dynamic information extraaction

I'm working on a code for extract information from an .json file and print it on a website. I achived all but now I have a problem, the data is showing only 1 result, it create all boxes/places for the other information but only the first "box" have information.
<head>
<!-- Title and Extern files -->
<title>SSL Checker</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/db.json"></script>
</head>
<body>
<div id="header">
<h2>SSL Checker</h2>
</div>
<div id="form">
<p>Introduce the URL:</p>
<input id="txtbx" type="text">
<button type="submit" onClick="agregar_caja()">Send</button>
<div id="inf">
<p type="text" id="hl1"></p>
<p type="text" id="hl2"></p>
</div>
<script>
//Extract
console.log(MyJSON[1].url)
var cajas = 2
var boxsaved = MyJSON.length
fnc = function(info) {
hey = document.getElementById("hl1").innerHTML = info.url;
}
//box creator
sm = function agregar_caja() {
document.getElementById("inf").innerHTML += "<p type=text id='hl" + new String(cajas + 1) + "'><br>"
cajas = cajas + 1
}
//Loops
for (i = 0; i < boxsaved; i++) {
sm(MyJSON[i]);
}
for (i = 0; i < MyJSON.length; i++) {
fnc(MyJSON[i]);
}
</script>
</body>
And .json file:
var MyJSON = [{
"url": 'google.es',
},
{
"url": 'yahoo.com',
}]
The problem is that your first box is the only element that your fnc function alters - notice that it only uses the hl1 id to access and alter an element, never hl2+.
I'll try to keep to your original approach, so that you'll follow it more easily. You might do something like this:
var cajas = 2;
function sm(info) {
cajas = cajas + 1;
document.getElementById("inf").innerHTML += (
'<div id="hl' + cajas + '">' + info.url + '</div>'
);
}
for (var i = 0; i < MyJSON.length; i++) {
sm(MyJSON[i]);
}
It is very difficult to read all the code, but as i've got it, you want to add some elements with url's from your JSON.
Ok, we have parent element div with id='inf', lets use javascript function appendChild to add new elements.
And we will use document.createElement('p') to create new elements.
Here is the code, as I've understood expected behavior.
var infContainer = document.getElementById('inf');
var elNumber = 2;
function agregar_caja() {
MyJSON.forEach(function(item,i) {
var newElement = document.createElement('p');
newElement.innerHTML = item.url;
newElement.id = 'hl'+elNumber;
elNumber++;
infContainer.appendChild(newElement);
}
)}

Dynamically array input with Javascript

I want to input the amount of array and the output will follow as it's amount.
Ex: If I put "7" in the input text. the result will show as much as 7.
Here's my code:
<html>
<head>
<title>JavaScript - Input Text Field</title>
</head>
<body>
<form name="test">
<H2>Enter something into the field and press the button. <br></H2>
<P>Amount of Tables: <input type="TEXT" name="amount"><BR><BR>
<input type="Button" Value="Show and Clear Input" onClick="myFunction()"></P>
</form>
<p id="demo"></p>
<script>
function myFunction() {
var text = "";
var i;
var j = document.getElementsByName("amount");
for (i = 0; i < j.length; i++) {
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
You have something wrong on your JavaScript
See code:
function myFunction() {
var text = "";
var i;
var j = document.getElementsByName("amount")[0];
for (i = 0; i < j.value; i++) {
text += "The number is " + j.value + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
.getElementsByName returns an array of elements, so you need to specify the index of your element so that you can access its properties.
Fiddle here

Is it possible to use another button to tell me the last alert?

I am looking to have two buttons and one auto generates a random string in an alert and I want another user to be able to go and enter the code in a text box and tell them if its valid or not.
First is this possible? Second, for someone new to JavaScript is this difficult?
Here is the current code I am using right now.
<script language="javascript" type="text/javascript">
function randomString() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 5;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
return randomstring;
}
</script>
<script>
function myFunction()
{
alert(randomString());
}
</script>
Thanks1
how about that one:
----------- file: index.html -----------
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Captcha Test</title>
<script src="test.js"></script>
</head>
<body onload="loadCaptcha('captcha-region')">
<div id="captcha-region"
style="text-indent: 10px; background: #fffccc"></div>
<label for="captcha"> Re-type text: </label>
<input id="captcha" type="text" value="" />
<input type="button" value="Submit"
onclick="checkCaptcha('result-region')" />
<input type="button" value="Reload"
onclick="loadCaptcha('captcha-region')" />
<div id="result-region"></div>
</body>
</html>
--------- file: test.js -----------------
function randomInt (range) {
return Math.floor(Math.random() * range);
}
function randomPos (s) {
return randomInt(s.length);
}
function randomChar (s) {
return s.charAt(randomPos(s));
}
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
function randomString () {
var s = '',
i = 0;
while (i++ < 5) {
s += randomChar(chars);
}
return s;
}
function htmlInsert (id, htmlData) {
document.getElementById(id).innerHTML = htmlData;
}
var captcha;
function loadCaptcha (captchaRegion) {
captcha = randomString();
htmlInsert(captchaRegion, '<h1>' + captcha + '</h1>');
}
function checkCaptcha (resultRegion) {
var okText = (captcha === document.getElementById('captcha').value)
? '<span style="color: yellowgreen"> ok </span>'
: '<span style="color: orange"> not ok </span>';
htmlInsert(resultRegion, '<h2>Typed text: ' + okText + '</h2>');
}
This basically is kinda captcha demo, maybe that contains some good parts..
You may want to put index.html & test.js in a directory of your liking (no local web server needed), then from inside that directory execute: "firefox index.html" and you're good to go..
What do you think?

Javascript not working after for loop is done

I can't manage to make the line in the code with all the asterisks to work. Can anyone help? The function works fine, it is just the document.write('This will not print'); that doesn't actually work. What is the problem?
//UPDATE//
First of all, thanks for the quick replies. Now I will post the full code.
As you can see the variable ii is declared at the body.
FULL CODE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
<!--
function runThis() {
var fruta01 = document.getElementById('fruta').value;
var color01 = document.getElementById('color').value;
var problemo = true;
for (newCount = 0; newCount<=ii; newCount++){
if (storeArray[newCount].match(fruta01) && storeArray[newCount].match(color01)){
document.write(storeArray[newCount]+'<br/>');
problemo = false;
};
};
document.write('This doesnt print')
};
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!--
//Matriz total
var storeArray = new Array ()
//Numero de objetos
var ii = 0;
//Color de los objetos
var colorCounter = 0
var color = new Array ()
color[0] = 'verde';
color[1] = 'amarillo';
//tipo de objetos
var objectCounter = 0
var object = new Array ()
object[0] = 'limones';
object[1] = 'platanos';
object[2] = 'manzanas';
for (ii; ii<8; ii++) {
storeArray[ii] = 'Tengo ' + ii + ' ' + object[objectCounter] +' de color ' + color[colorCounter];
if (objectCounter != 2) {
++objectCounter
}else{
objectCounter = 0
}
if (colorCounter != 1) {
++colorCounter
}else{
colorCounter = 0
}
}
//print array so that you may see what you can choose...
for(var i=0;i<storeArray.length;i++){
document.write(storeArray[i]+"<br>");
}
//-->
</script>
<form>
Que fruta buscas? <input type="text" size="10" id='fruta'/><br />
De que color? <input type="text" size="10" id='color'/><br />
<input type="submit" value="Submit!" onclick="runThis()"/>
</form>
</body>
</html>
EDIT
The problem is in your for loop
for (newCount = 0; newCount <= ii; newCount++ )
Should be
for (newCount = 0; newCount < ii; newCount++ )
You don't have to put a semicolon after function, and 'if' and 'for' loops.
Here is a better version of your code
function runThis () {
var fruta01 = document.getElementById('fruta').value;
var color01 = document.getElementById('color').value;
var problemo = true;
for (newCount = 0; newCount <= ii; newCount++ )
{
if (storeArray[newCount].match(fruta01) && storeArray[newCount].match(color01) )
{
document.write(storeArray[newCount]+'<br/>');
problemo = false;
}
}
document.write('This will not print'); //**************************
}
Just use console.log() or a simple alert if you want to check just that.
Thats because the loop fails
You never set ii anywhere.
Check your console to make sure there are no javascript errors.

Categories

Resources