JavaScript - need help combining two scripts. - javascript

I’m trying to call a user input array.
I’m very new on Javascript but know I somehow need to reference the array (it is somewhere where I put the ???).
<script>
var arrayX =5;
var arrayY =1;
var array=new Array(arrayX);
var planetIndex=0;
for (x=0; x<array.length; x++)
{array [x] = new Array(arrayY);}
function insert(val1){
array[planetIndex][0]=val1;
planetIndex++;
document.getElementById('name').value = ''; };
function worldChange() {
var newplanet = ????????????
var whichWorld = Math.floor(Math.random()*newplanet.length);
return planetIndex[whichWorld];
var planets = document.getElementsByClassName("world-name")
for (var i=0; i < planets.length; i++) {
planets[i].innerHTML = worldChange();};
};
</script>
<body>
<div>
<form>
<input type="integer" id="name"/>
<input type="button" value="Add Planets" onclick="insert (this.form.name.value);"/>
</form>
<input type="button" value="See planet!" onClick="worldChange()" />
<br> Hello <span class="world-name">Earth!</span><br />
</div>
</body>
I got both elements of the script to work perfectly on my site so every time someone hits a button it changes the guy in the story. But as you see if pulls from the array I created. I want to pull from an array that a user creates so they could input their own list of names.
so this script works fine:
function newGuy() {
var guys = new Array ("Jeff", "Mike", "George", "Harold");
var whichGuy = Math.floor(Math.random()*guys.length);
return guys[whichGuy];}
var guy = document.getElementsByClassName("guy")
for (var i=0; i < guy.length; i++) {
guy[i].innerHTML = newGuy();}
And this script works alone:
var arrayX =5;
var arrayY =1;
var array=new Array(arrayX);
var guyIndex=0;
for (x=0; x<array.length; x++)
{array [x] = new Array(arrayY);}
function insert(val1){
array[guyIndex][0]=val1;
guyIndex++;
document.getElementById('name').value = ''; };
Just baffled on how to put them together.

There are a lot of problems with your script but to give you an idea on how to get it to work :
var planets = [];
// define how many planets there will be initially
var initialLength = 5;
// add the initital planets
for (x = 0; x < initialLength; x++) {
planets.push("planet" + x);
}
function insert() {
var planetToInsert = document.getElementById('name').value;
if (planetToInsert) {
// add the input to the array of planets
planets.push(planetToInsert);
document.getElementById('name').value = '';
} else {
alert("please enter a value");
}
}
function worldChange() {
// randomly pick an index
var whichWorld = Math.floor(Math.random() * planets.length);
document.getElementById('world-name').innerHTML = planets[whichWorld];
}
working sample here
For finding problems in you code jsFiddle can be of excellent help. Run JSlint to find the basic errors, put in alerts as poor mans debugging.
For a good javascript book I would recommend javascript patterns

Related

Hide/Show div p5.js

I am using the p5.js library, and I am working on a speech recognition - text to speech project. Kind of a chatbot.
Input is voice input which becomes a string.
I am outputting the result from a txt file, using a markov chain. Output is a string contained in a div.
My question is:
Is there a way to hide/show the div containing my input/output (.myMessage and .robotMessage) in intervals?
I want the whole screen first showing only the input when I am talking, then input disappears and only output showing, then when the computer voice finishes speaking my input is shown in the screen and so on...
Here some parts of the code, let me know if it is clear enough.
//bot
function setup() {
noCanvas();
//reads and checks into the text file
for (var j = 0; j < names.length; j++) {
var txt = names[j];
for (var i = 0; i <= txt.length - order; i++) {
var gram = txt.substring(i, i + order);
if (i == 0) {
beginnings.push(gram);
}
if (!ngrams[gram]) {
ngrams[gram] = [];
}
ngrams[gram].push(txt.charAt(i + order));
}
}
//voice recognition
let lang = 'en-US';
let speechRec = new p5.SpeechRec(lang, gotSpeech);
let continuous = true;
let interim = false;
speechRec.start(continuous, interim);
//text-to-speach
speech = new p5.Speech();
speech.onLoad = voiceReady;
function voiceReady() {
console.log('voice ready');
}
//input-ouput
function gotSpeech() {
if (speechRec.resultValue) {
var p = createP(speechRec.resultString);
p.class('myMessage');
}
markovIt();
chooseVoice();
speech.speak(answer);
}
}
and
function markovIt() {
var currentGram = random(beginnings);
var result = currentGram;
for (var i = 0; i < 100; i++) {
var possibilities = ngrams[currentGram];
if (!possibilities) {
break;
}
var next = random(possibilities);
result += next;
var len = result.length;
currentGram = result.substring(len - order, len);
}
var answer = result;
window.answer = answer;
var p2 = createP(answer);
p2.class('robotMessage');
}
how the HTML looks
<div class="container">
<div class="myMessage"></div>
<div class="robotMessage"></div>
</div>
Use select() to get a document element by its id, class, or tag name. e.g:
let my_div = select("myMessage");
Change the style of an element by style().
e.g hide:
my_div.style("display", "none");
e.g. show:
my_div.style("display", "block");
See also Toggle Hide and Show

Form value always read as undefined in Javascript

I'm a new self taught programmer working on my first homework assignment, so I apologize if my naming convention is off. This is the most bizarre thing. No matter how I request the input value, (hoping to pull a number) it always reads as undefined.
Everything works in my javascript function except pulling the input value. I have used forms in the past, and the variables appear to be referencing it fine; I have tried both document.formName.inputName.value, as well as document.getElementById ('input-id').value and it returns undefined. I have renamed my form and variables so many times to see if that was the issue and stI'll nothing. I have tried both input type text and number, and stI'll undefined.
Am I missing something due to how new I am? Please help. Links to github and jsfiddle below.
https://github.com/MissElle/calculator?files=1
https://jsfiddle.net/MissElle/qf7xL8gj/
var dataInput = document.compute.calculate.value;
var element = Number(dataInput);
var numCount = document.getElementById('count');
var numSum = document.getElementById('sum');
var numMean = document.getElementById('mean');
var subCount = [];
var subSum = 0;
var starColors = ['#51fffc', '#ffff96', '#96ffc7', '#f8d8ff', '#d2bfff', '#ffbfbf', '#ffd299', '#ffffff', '#000000'];
function calcData(element) {
if(typeof element === 'number') {
console.log(element);
subCount.push(element);
var starDiv = document.createElement('div');
starDiv.className = 'star';
var starHolder = document.getElementById('star-holder');
starHolder.appendChild(starDiv);
starDiv.style.background = 'radial-gradient(circle, ' + starColors[Math.floor(Math.random() * starColors.length)] + ', transparent, transparent)';
numCount.innerHTML = subCount.length;
for(var i in subCount) {
subSum += subCount[i];
numSum.innerHTML = subSum;
var subMean = subSum/subCount.length;
numMean.innerHTML = subMean;
}
}else {
numCount.innerHTML = 'Not a Number';
console.log(element);
}
subSum = 0;
event.preventDefault();
}
function clearData() {
subCount = [];
subSum = 0;
subMean = 0;
numSum.innerHTML = '';
numMean.innerHTML = '';
numCount.innerHTML = '';
var starHolder = document.getElementById('star-holder');
var starDiv = starHolder.getElementsByClassName('star');
while(starDiv.length > 0) {
starHolder.removeChild(starDiv[0]);
}
}
<form name="compute" onsubmit="calcData()" onReset="clearData()">
<p class="bold">Please enter a number</p>
<input type="number" name="calculate" id="calculation" step="any"><br>
<input type="submit" name="submit" value="star">
<input type="reset" value="nostar" name="clearForm">
<div class="row">
<div class="typevalue"><h4>Count:</h4><h4>Sum:</h4><h4>Mean:</h4></div>
<div class="numbervalue"><p id="count"></p><p id="sum"></p><p id="mean"></p></div>
</div>
</form>
Move your variable declarations inside your function like this:
function calcData(element) {
var dataInput = document.compute.calculate.value;
var element = Number(dataInput);
var numCount = document.getElementById('count');
var numSum = document.getElementById('sum');
var numMean = document.getElementById('mean');
var subCount = [];
var subSum = 0;
var starColors = ['#51fffc', '#ffff96', '#96ffc7', '#f8d8ff', '#d2bfff',
'#ffbfbf', '#ffd299', '#ffffff', '#000000'];
...
If you declare your dataInput outside the function you get no value because that JS code is run after the page loads (before your user types any number in your function).
You have to declare it inside your function that way you get the value of your input when the user clicks on the button.

Getting this javascript to work on a modern browser

I'm trying to modernize an intranet site somebody has built in the past which at the moment is forced into compatibility mode for IE5 through group policy. There is this javascript which creates x ammount of file input boxes within a form. This works on compatibility mode up to IE9 but not higher. I don't really know javascript I was hoping someone could help me modernize it?
<SCRIPT LANGUAGE="JavaScript">
var i = 0, j = 0;
var t1 = new Array();
function createtext() {
var inputLoop = document.getElementById("Many");
var table1 = document.getElementById("field");
for (i = 0; i < inputLoop.value; i++)
{
t1[i] = document.createElement('input');
t1[i].type = 'file';
t1[i].name = 'Image' + i;
t1[i].value = "Hello";
t1[i].size = 20;
document.forms[0].appendChild(t1[i]);
}
}
</SCRIPT>
<input name="b1" type="button" onClick="createtext();" value="Add">
If I run it on higher than IE9 the 'Add' button does nothing
The code works even in modern browsers. Just remove t1[i].value = "Hello"; because you can't set a value to input field programmatically.
var i = 0,
j = 0;
var t1 = [];
function createtext() {
var inputLoop = document.getElementById("Many");
var table1 = document.getElementById("field");
if (inputLoop.value) {
for (i = 0; i < inputLoop.value; i++) {
t1[i] = document.createElement('input');
t1[i].type = 'file';
t1[i].name = 'Image' + i;
t1[i].size = 20;
document.forms[0].appendChild(t1[i]);
}
}
}
<input type="text" id="Many">
<input name="b1" type="button" onClick="createtext();" value="Add">
<form action=""></form>

Accessing Stored Object

I have an object "Driver" defined at the beginning of my script as such:
function Driver(draw, name) {
this.draw = draw;
this.name = name;
}
I'm using this bit of JQuery to create new drivers:
var main = function () {
// add driver to table
$('#button').click(function ( ) {
var name = $('input[name=name]').val();
var draw = $('input[name=draw]').val();
var draw2 = "#"+draw;
var name2 = "driver"+draw
console.log(draw2);
console.log(name2);
if($(name2).text().length > 0){
alert("That number has already been selected");}
else{$(name2).text(name);
var name2 = new Driver(draw, name);}
});
That part is working great. However, when I try later on to access those drivers, the console returns that it is undefined:
$('.print').click(function ( ) {
for(var i=1; i<60; i++){
var driverList = "driver"+i;
if($(driverList.draw>0)){
console.log(driverList);
console.log(driverList.name);
}
If you're interested, I've uploaded the entire project I'm working on to this site:
http://precisioncomputerservices.com/slideways/index.html
Basically, the bottom bit of code is just to try to see if I'm accessing the drivers in the correct manner (which, I'm obviously not). Once I know how to access them, I'm going to save them to a file to be used on a different page.
Also a problem is the If Statement in the last bit of code. I'm trying to get it to print only drivers that have actually been inputed into the form. I have a space for 60 drivers, but not all of them will be used, and the ones that are used won't be consecutive.
Thanks for helping out the new guy.
You can't use a variable to refer to a variable as you have done.
In your case one option is to use an key/value based object like
var drivers = {};
var main = function () {
// add driver to table
$('#button').click(function () {
var name = $('input[name=name]').val();
var draw = $('input[name=draw]').val();
var draw2 = "#" + draw;
var name2 = "driver" + draw
console.log(draw2);
console.log(name2);
if ($(name2).text().length > 0) {
alert("That number has already been selected");
} else {
$(name2).text(name);
drivers[name2] = new Driver(draw, name);
}
});
$('.print').click(function () {
for (var i = 1; i < 60; i++) {
var name2 = "driver" + i;
var driver = drivers[name2];
if (driver.draw > 0) {
console.log(driver);
console.log(driver.name);
}

Can't figure out how to find the primes

I have a program that is supposed to take two numbers entered by the user and send them to a function. This function will be used to determine all the prime numbers between those two numbers. However, I just can't seem to figure out how to find all the primes. I created an array that should hold all numbers between the two user submitted ones. But I don't know how to iterate through it and place all the prime numbers found into a new array. I know it's basic stuff, but for some reason I just can't figure it out.
Here's the code for my function so far.
function displayPrimeNumbers(p1, p2) {
var numbers = [];
var primes = [];
for(i = p2; i == p1; i++){
numbers.push(i);
for(i = 0; i < numbers.length; ++i){
if () {
}
}
}
}
<html>
<head>
<script = "text/javascript>
function prime(num1,num2)
{
var s="";
var count=0;
for(i=parseInt(num1);i<num2;i++)
{
for(j=2;j<i;j++)
{
if(i%j==0)
{
count ++ ;
}
}
if(count == 0)
{
s=s+"\n"+i;
}
count = 0;
}
document.getElementById('textarea1').value = s;
}
</script>
</head>
<body>
<input type = "text" id = "num1">
<input type = "text" id = "num2">
<input type = "button" value = "Click here" onclick = "prime(document.getElementById('num1').value,document.getElementById('num2').value)"><br>
<textarea id = "textarea1" rows="10" cols = "20">answer</textarea>
</body>
</html>

Categories

Resources