Unknown error writing an array to an element in javascript? - javascript

I am looking to add an array to a div. Not working with document.getElementsByClassName('boxed').innerHTML = numList. I am able to write the array to the DOM with document.write(numList).
Here's the whole HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Super Lotto</title>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Libre+Franklin" rel="stylesheet">
<link href="lotto-styles.css" rel="stylesheet">
<script>
do {
var high = prompt('What\'s the highest number you want to generate','');
high = parseInt(high, 10);
} while (isNaN(high));
do {
var nums = prompt('How many numbers do you want to generate','');
nums = parseInt(nums, 10);
} while (isNaN(nums));
function rand(highestNum) {
var randomNumber =
Math.floor(Math.random() * highestNum) + 1;
return randomNumber;
}
var numList = [];
for (var i = 0; i < nums; i++) {
// Go through this loop quantity of times
numList.unshift(rand(high));
// add new number to end of array
};
numList.toString();
document.getElementsByClassName('boxed').innerHTML = numList;
</script>
</head>
<body>
<div id="container">
<header>
<h1>Lucky Numbers</h1>
</header>
<main>
<div class="boxed"></div>
<p>Good luck!</p>
</main>
</div> <!-- Closing container -->
</body>
</html>

your problem is that in innerHTML you can't add an array, just a string, to add the numbers you need to do something like numList.join(" ");, I modified your code to do that. another thing I change is that instead of use "boxed" as a class, I use it as an id because getElementsByClassName return an nodeList.
do {
var high = prompt('What\'s the highest number you want to generate','');
high = parseInt(high, 10);
} while (isNaN(high));
do {
var nums = prompt('How many numbers do you want to generate','');
nums = parseInt(nums, 10);
} while (isNaN(nums));
function rand(highestNum) {
var randomNumber =
Math.floor(Math.random() * highestNum) + 1;
return randomNumber;
}
var numList = [];
for (var i = 0; i < nums; i++) {
// Go through this loop quantity of times
numList.unshift(rand(high));
// add new number to end of array
};
numList.toString();
document.getElementById('boxed').innerHTML = numList.join(" ");
<div id="container">
<header>
<h1>Lucky Numbers</h1>
</header>
<main>
<div id="boxed"></div>
<p>Good luck!</p>
</main>
</div>

When you get elements by class names (source: https://developer.mozilla.org/fr/docs/Web/API/Document/getElementsByClassName), you receive an array,so you have to precise which element of the array you want, I think [0] in your case.
It's better to work with an ID if you only have one place to put the result, like this:
do {
var high = prompt('What\'s the highest number you want to generate','');
high = parseInt(high, 10);
} while (isNaN(high));
do {
var nums = prompt('How many numbers do you want to generate','');
nums = parseInt(nums, 10);
} while (isNaN(nums));
function rand(highestNum) {
var randomNumber =
Math.floor(Math.random() * highestNum) + 1;
return randomNumber;
}
var numList = [];
for (var i = 0; i < nums; i++) {
// Go through this loop quantity of times
numList.unshift(rand(high));
// add new number to end of array
console.log(numList)
};
numList.toString();
document.getElementById('boxed').innerHTML = numList;
<!DOCTYPE html>
<html lang="en">
<head>
<title>Super Lotto</title>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Libre+Franklin" rel="stylesheet">
<link href="lotto-styles.css" rel="stylesheet">
</head>
<body>
<div id="container">
<header>
<h1>Lucky Numbers</h1>
</header>
<main>
<div id="boxed"></div>
<p>Good luck!</p>
</main>
</div> <!-- Closing container -->
</body>
</html>

Related

How to add a random element from an array to another blank array?

I want to create a simple restaurant menu by javascript . First the menu will display 5 dishes (which stores in array "menu"). Then when I click the button "Order" , a random dish from the array "menu" will be display in the line "Orders" one by one as I keep clicking it. To do this I generated random number from 0-4 and created 2nd blank array "Orders" and create DOM objects to write "Orders" array's element one by one in the HTML line. Code is below
const menu = ["Steak", "Potato", "Hamburger", "Salad", "Cheesecake"];
let show_menu = document.querySelector("#menu");
let show_orders = document.querySelector("#orders");
for (let i = 0; i <= menu.length; i++) {
if (menu[i] != undefined) {
show_menu.textContent += `      ${menu[i]}`;
}
}
function chuumon() {
let orders = [];
let a = Math.floor(Math.random() * 5);
document.querySelector("#num").textContent = a;
orders.push(menu[a]);
show_orders.textContent = orders[a];
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>restaurant order</title>
</head>
<body>
<h4>Menu</h4>
<span id="menu"></span>
<hr> Orders:
<span id="orders"></span><br>
<span id="num"></span>
<button onclick="chuumon()">Order</button>
</body>
</html>
The problem is when I hit the button "Order" in the line "Orders" it only shows the element[0] of array menu otherwise it didn't show anything.
What's wrong with my push() method? (orders.push(menu[a]))
Now I want to set up an event when click the button "Serve" the dish at first in Line "Orders" will be deleted one by one. So I set up another function "Teikyo()" to use function_name.shift() methoad but struggling with access the "Order" Array values inside function "chuumon()" .Here is my code about these 2 functions. Can anyone suggest for me how to access into other function's property?
function chuumon() {
let a = Math.floor(Math.random() * 5);
show_orders.textContent = menu.join(",");
orders.push(menu[a]);
show_orders.textContent = orders;
last_order.textContent = orders[orders.length - 1]
}
function teikyo()
{
chuumon().orders.shift();
show_orders.textContent = orders;
}
That is nothing wrong with orders.push(menu[a]) it is pushing the array properlly, however, you actually don't need the orders.push(menu[a]) as you are initiating it everytime you call the function.
You can simply do:
function chuumon() {
let a = Math.floor(Math.random() * 5);
document.querySelector("#num").textContent = a;
show_orders.textContent = menu[a];
}
const menu = ["Steak", "Potato", "Hamburger", "Salad", "Cheesecake"];
let show_menu = document.querySelector("#menu");
let show_orders = document.querySelector("#orders");
for (let i = 0; i <= menu.length; i++) {
if (menu[i] != undefined) {
show_menu.textContent += `      ${menu[i]}`;
}
}
function chuumon() {
let a = Math.floor(Math.random() * 5);
document.querySelector("#num").textContent = a;
show_orders.textContent = menu[a];
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>restaurant order</title>
</head>
<body>
<h4>Menu</h4>
<span id="menu"></span>
<hr> Orders:
<span id="orders"></span><br>
<span id="num"></span>
<button onclick="chuumon()">Order</button>
</body>
</html>
Or, if you want to push something on that array and keep track, you need to declare it outside your function.
const menu = ["Steak", "Potato", "Hamburger", "Salad", "Cheesecake"];
let orders = [];
let show_menu = document.querySelector("#menu");
let show_orders = document.querySelector("#orders");
let show_order = document.querySelector("#order");
for (let i = 0; i <= menu.length; i++) {
if (menu[i] != undefined) {
show_menu.textContent += `      ${menu[i]}`;
}
}
function chuumon() {
let a = Math.floor(Math.random() * 5);
document.querySelector("#num").textContent = a;
show_orders.textContent = menu[a];
orders.push(menu[a]);
show_orders.textContent = orders;
show_order.textContent = orders[orders.length - 1]
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>restaurant order</title>
</head>
<body>
<h4>Menu</h4>
<span id="menu"></span>
<hr> Orders:
<span id="orders"></span><br>
<span id="num"></span>
<hr> Last Order:
<span id="order"></span><br>
<button onclick="chuumon()">Order</button>
</body>
</html>
a is an index into menu. It won't be the correct index into orders, since this array will usually be shorter than menu. You should show menu[a] in show_orders, not orders[a].
orders should be declared and initialized outside the function. Otherwise you keep resetting it to an empty array, instead of collecting all the ordered items.
const menu = ["Steak", "Potato", "Hamburger", "Salad", "Cheesecake"];
let orders = [];
let show_menu = document.querySelector("#menu");
let show_orders = document.querySelector("#orders");
for (let i = 0; i < menu.length; i++) {
show_menu.textContent += `      ${menu[i]}`;
}
function chuumon() {
let a = Math.floor(Math.random() * menu.length);
document.querySelector("#num").textContent = a;
orders.push(menu[a]);
show_orders.textContent = menu[a];
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>restaurant order</title>
</head>
<body>
<h4>Menu</h4>
<span id="menu"></span>
<hr> Orders:
<span id="orders"></span><br>
<span id="num"></span>
<button onclick="chuumon()">Order</button>
</body>
</html>
Problem: If it hasn't already been mentioned, your empty array orders is defined within the function. When a function is finished, all values within said function are garbage collected (deleted from memory -- gone). Every click of the button runs a the function with an empty orders array every time. The only text that'll show up is "steak" because you happen to get 0 of course, but what happens when the index is 3 (or anything other than 0)?:
orders = [];
menu[0] = 'steak';
orders.push('steak');
orders[0] = 'steak';
// Next click
orders = [];
menu[3] = 'salad';
orsers.push('salad');
orders[3] = ??????
// The length of orders is always 1
Solution: Do not create a new array, it's pointless. The nature of the function is that of an event handler. It works with the array once every click and nothing else.
const items = ["Steak", "Potato", "Hamburger", "Salad", "Cheesecake"];
const menu = document.querySelector(".menu");
items.forEach(item => menu.insertAdjacentHTML('beforeEnd', `<li>${item}</li>`));
function orderItem(e) {
let order = document.querySelector('.order');
let index = Math.floor(Math.random() * items.length);
order.textContent = ` ${index+1}. ${items[index]}`;
}
document.querySelector('button').addEventListener('click', orderItem);
.menu {
display: flex;
justify-content: space-between;
margin: -10px 0 -6px 0;
}
b {
font: 2ch/1
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>restaurant order</title>
</head>
<body>
<h4>Menu</h4>
<ol class="menu"></ol>
<hr>
<button>Order</button><b> :</b>
<output class='order'></output>
</body>
</html>
For my edit path about adding another event with button "Serve" to delete one by one the dish showed in "Orders" linne. Here is my relate code and I tested it successfully.If you want to access a DOM object property just add the .value after the name of object.
function chuumon() {
let a = Math.floor(Math.random() * 5);
show_orders.textContent = menu.join(",");
orders.push(menu[a]);
show_orders.textContent = orders;
last_order.textContent = orders[orders.length - 1];
}
function teikyo(){
orders.shift(show_orders.value);
show_orders.textContent = orders;
first_serve.textContent = orders.shift(show_orders.value);
}

Cannot read property 'setAttribute' of null - Javascript

I have seen a couple of questions posted with this error on here and having seen some of the answers I noticed the general consensus is that it is caused due to the DOM not being created yet. I have tried a few different solutions to fix it such as moving my script to immediately prior to the tag, using log outputs before and after the image creation in order to ensure the object is actually being created correctly but nothing has resolved my issue. I am new to Javascript so it might be something obvious I am missing?
var dice = [6, 6, 6, 6, 6];
function rollDice() {
for (var i = 0; i < dice.length; ++i) {
var num = Math.floor(Math.random() * 6 + 1);
dice[i] = 1;
document.write(dice[i] + "<br>");
}
for (var i = 0; i < dice.length; ++i) {
var value = dice[i];
var path;
var ArrayImage = ["images/dice 1.png", "images/dice 2.png", "images/dice 3", "images/dice 4.png", "images/dice 5.png", "images/dice 6.png"];
path = ArrayImage[value];
}
document.getElementById("dice_1").setAttribute("src", path)
}
<html>
<head>
<meta charset="utf-8">
<title>Project 1</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1> This is a javascript application</h1>
<script>
console.log("script #1: %o", document.getElementById("dice_1")); // null
</script>
<div>
<img id="dice_1" src="images/dice 1.png">
<img id="dice_2" src="images/dice 1.png">
<img id="dice_3" src="images/dice 1.png">
<img id="dice_4" src="images/dice 1.png">
<img id="dice_5" src="images/dice 1.png">
</div>
<input id="but" type="button" onclick="rollDice()" value="Roll Dice.">
<script>
console.log("script #1: %o", document.getElementById("dice_1")); // null
</script>
<script type="text/javascript" src="scripts/script.js"></script>
</body>
</html>
Since you're using document.write after the document has loaded, it's clearing the entire document (due to document.open() being called). Therefore, your img elements do not exist for setAttribute to be run against them. Try the following (note the index corrections that are needed due to array indexing starting at zero):
var dice = [6,6,6,6,6];
var results;
var resultsContainer = document.querySelector('.results');
function rollDice(){
// clear results array
results = [];
for(var i =0; i<dice.length; ++i){
var num = Math.floor(Math.random()*6 +1);
dice[i] = num;
results.push(dice[i]);
}
for(var i =0; i< dice.length; ++i){
var value = dice[i];
var path;
var ArrayImage = ["images/dice 1.png", "images/dice 2.png", "images/dice 3.png", "images/dice 4.png", "images/dice 5.png", "images/dice 6.png"];
path = ArrayImage[value - 1];
document.getElementById("dice_"+ (i + 1)).setAttribute("src",path);
}
// convert results array to text with <br> between them
var resultsStr = results.join("<br>");
// display results as text to page
resultsContainer.innerHTML = resultsStr;
}

random numbers between 1 and 50; 50 times

I´m almost got it, but it still not working out like I want
it -- I got s var a = generates an integer between 1 and 50
the integer (result) is output in a textare id("tt4")
but I can't get it done 50 times, I tried to use a for loop // but like I said, I´m
hanging here...
function add() {
var a = Math.floor(Math.random() * 50) + 1;
for (var i = 0; i < 49; i++) {
document.getElementById("tt4").innerHTML = a + ('\n');
}
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
</head>
<body>
<button onclick="add()">OK</button>
<br><br>
<textarea id="tt4" name="t4"></textarea>
</body>
</html>
I know that the problem is in the for-loop, because 'nothing' hapens with the var i inside the loop // but I can't figure it out
You need to concatenate the innerHTML property in order to update the display. You also need to move your random number generation into your loop. Here is a sample:
function add() {
for (var i = 0; i < 49; i++) {
var a = Math.floor(Math.random() * 50) + 1;
document.getElementById("tt4").innerHTML += a + ('\n');
}
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
</head>
<body>
<button onclick="add()">OK</button>
<br><br>
<textarea id="tt4" name="t4"></textarea>
</body>
</html>
You will need to use += instead of = when setting the innerHTML of the textarea (which will add more HTML instead of replacing the HTML with the current random number).
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
</head>
<body>
<button onclick="add()">OK</button>
<br><br>
<textarea id="tt4" name="t4"></textarea>
<script>
function add() {
for (var i = 0; i < 49; i++) {
var a = Math.floor(Math.random() * 50) + 1;
document.getElementById("tt4").innerHTML += a + ('\n');
}
}
</script>
</body>
</html>
If you place the random() inside the loop, each iteration generates a new number, otherwise you have the same number. Also += add content, intead of =, that assign and replace the content.
for (var i = 0; i < 49; i++) {
var a = Math.floor(Math.random() * 50) + 1;
document.getElementById("tt4").innerHTML += a + ('\n');
}
<textarea id="tt4" name="t4"></textarea>

Javascript SetInterval and get value Math.random

I have just created random number. My problems is how to get value random in id and how to set price changes automatically every 5 seconds and the fluctuation amplitude less than +/- 5% compared to the current, I don't know use the setinterval function everybody help me
My code Random Price :
function generateRandomNumber(min,max) {
return (Math.random() * (max - min) + min).toFixed(2);
};
document.getElementById('price1').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price2').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price3').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price4').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price5').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price6').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price7').innerHTML = generateRandomNumber(0,99.99);
It took me a while to work around the recursion issues I was running into, before I came up with a better solution.
//<![CDATA[
// external.js
function RandNumMaker(min, max, withinPercent, secondsInterval, decimalPlaces){
this.withinPercent = withinPercent || 5;
this.secondsInterval = secondsInterval || 5;
this.decimalPlaces;
if(decimalPlaces){
this.decimalPlaces = decimalPlaces;
}
var t = this, ia = [];
function rb(mn, mx){
return mx-Math.random()*(mx-mn);
}
var pn = rb(min, max);
function rn(){
var p = 1;
if(Math.floor(Math.random()*2) === 1)p = -1
return p*(Math.floor(Math.random()*t.withinPercent)+1)/100*pn;
}
function rf(){
var r, d = t.decimalPlaces;
pn += rn();
if(pn < min || pn > max){
return rf();
}
r = pn;
if(d)r = (Math.floor(Math.round(Math.pow(10, d+1)*r)/10)/Math.pow(10, d)).toFixed(d);
return r;
}
this.setDiv = function(div){
div.innerHTML = rf(); ia = [];
var iv = setInterval(function(){
div.innerHTML = rf();
}, this.secondsInterval*1000);
ia.push(iv);
return this;
}
this.stop = function(){
for(var i=0,l=ia.length; i<l; i++){
if(ia[i]){
clearInterval(ia[i]);
}
}
ia = [];
return this;
}
}
var doc, bod, C, E, N, old = onload; // for use on other loads
onload = function(){
if(old)old();
doc = document; bod = doc.body;
C = function(tag){
return doc.createElement(tag);
}
E = function(id){
return doc.getElementById(id);
}
N = function(className, inElement){
var ii = inElement || doc;
var cN = ii.getElementsByClassName(className);
if(cN){
return cN;
}
var tn = ii.getElementsByTagName('*');
for(var i=0,e,a=[],l=tn.length; i<l; i++){
e = tn[i];
if(e.className && e.className === className)a.push(e);
}
return a;
}
var sr = new RandNumMaker(0, 99.99), sl = N('slow');
var fr = new RandNumMaker(0, 99.99), fs = N('fast');
sr.decimalPlaces = 2;
fr.secondsInterval = 0.1; fr.withinPercent = 5;
for(var i=0,l=sl.length; i<l; i++){
sr.setDiv(sl[i]);
}
for(var i=0,l=fs.length; i<l; i++){
fr.setDiv(fs[i]);
}
}
//]]>
/* extrnal.js */
html,body{
padding:0; margin:0;
}
body{
background:#000; overflow-y:scroll;
}
.main{
width:940px; background:#fff; padding:20px; margin:0 auto;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<meta name='viewport' content='width=device-width' />
<title>test</title>
<link type='text/css' rel='stylesheet' href='external.css' />
<script type='text/javascript' src='external.js'></script>
</head>
<body>
<div class='main'>
<div class='slow'></div>
<div class='slow'></div>
<div class='slow'></div>
<div class='slow'></div>
<div class='slow'></div>
<div class='slow'></div>
<div class='slow'></div>
<hr />
<div class='fast'></div>
<div class='fast'></div>
<div class='fast'></div>
<div class='fast'></div>
</div>
</body>
</html>
Should work now!
After you create a new RandNumMaker(min, max) then you can set randomNumMarkerInstance.decimalPlaces, randomNumMakerInstance.withinPercent and randomNumMakerInstance.secondsInterval using simple assignment. randomNumMakerInstance.setDiv(div) starts it. randomNumMakerInstance.stop() stops it.
I think you can understand this code.
I tried to keep your code.
The key is to use setInterval function.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<script>
function generateRandomNumber(min,max) {
return (Math.random() * (max - min) + min).toFixed(2);
};
function assignData(){
document.getElementById('price1').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price2').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price3').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price4').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price5').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price6').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price7').innerHTML = generateRandomNumber(0,99.99);
setInterval(assignData, 5000); //every 5 seconds
}
</script>
<body onload="assignData()">
<h2 id="price1"></h2>
<h2 id="price2"></h2>
<h2 id="price3"></h2>
<h2 id="price4"></h2>
<h2 id="price5"></h2>
<h2 id="price6"></h2>
<h2 id="price7"></h2>
</body>
</html>
My interpretation of your question: all elements to start with a random value between 0 and 99.99, and then every five seconds one randomly selected element is to be updated, changing its value by a random amount within 5% of its current value. (If you want to update every element every five seconds then change the random selection to be a loop instead.)
For simplicity in the demo snippet (click "Run code snippet" to see it work), I've used a group of <li> elements which I select with .querySelectorAll("li"), but if you really want to do it using element IDs you could say .querySelectorAll("#price1,#price2,#price3,#price4,#price5,#price6,#price7").
function generateRandomNumber(min,max) {
return (Math.random() * (max - min) + min).toFixed(2);
}
// get list of elements:
var elements = document.querySelectorAll("li");
// populate all elements initially:
[].forEach.call(elements, function(el) {
el.innerHTML = generateRandomNumber(0,99.99);
});
// update an element at random every second:
setInterval(function update() {
var element = elements[Math.floor(Math.random() * elements.length)];
var currentVal = +element.innerHTML;
element.innerHTML = generateRandomNumber(currentVal * 0.95, currentVal * 1.05);
}, 1000);
<ul>
<li></li><li></li><li></li><li></li><li></li><li></li><li></li>
</ul>
Note that five second intervals seemed too slow for a demo, so I've used one second (1000ms) here.
Further reading:
.querySelectorAll()
Array .forEach() method
Function.prorotype.call()
Math.floor()
unary plus operator
Hope this will help.
<body>
<p id="price1"></p>
<p id="price2"></p>
<p id="price3"></p>
<p id="price4"></p>
<p id="price5"></p>
<p id="price6"></p>
<p id="price7"></p>
</body>
<script>
//set initial random number for the elements
document.getElementById('price1').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price2').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price3').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price4').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price5').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price6').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price7').innerHTML = generateRandomNumber(0,99.99);
//set random number to elements with fluctuation +/- 5%
setRandomToElements()
function generateRandomNumber(min,max) {
return (Math.random() * (max - min) + min).toFixed(2);
};
function setRandomToElements(){
//get current prices
var currentPrice1 = parseInt(document.getElementById('price1').innerHTML);
var currentPrice2 = parseInt(document.getElementById('price2').innerHTML);
var currentPrice3 = parseInt(document.getElementById('price3').innerHTML);
var currentPrice4 = parseInt(document.getElementById('price4').innerHTML);
var currentPrice5 = parseInt(document.getElementById('price5').innerHTML);
var currentPrice6 = parseInt(document.getElementById('price6').innerHTML);
var currentPrice7 = parseInt(document.getElementById('price7').innerHTML);
var fluctuation = 0.05;//5%
//random new numbers +/-5% current price
document.getElementById('price1').innerHTML = generateRandomNumber(currentPrice1-(currentPrice1*fluctuation), currentPrice1+(currentPrice1*fluctuation));
document.getElementById('price2').innerHTML = generateRandomNumber(currentPrice2-(currentPrice2*fluctuation), currentPrice2+(currentPrice2*fluctuation));
document.getElementById('price3').innerHTML = generateRandomNumber(currentPrice3-(currentPrice3*fluctuation), currentPrice3+(currentPrice3*fluctuation));
document.getElementById('price4').innerHTML = generateRandomNumber(currentPrice4-(currentPrice4*fluctuation), currentPrice4+(currentPrice4*fluctuation));
document.getElementById('price5').innerHTML = generateRandomNumber(currentPrice5-(currentPrice5*fluctuation), currentPrice5+(currentPrice5*fluctuation));
document.getElementById('price6').innerHTML = generateRandomNumber(currentPrice6-(currentPrice6*fluctuation), currentPrice6+(currentPrice6*fluctuation));
document.getElementById('price7').innerHTML = generateRandomNumber(currentPrice7-(currentPrice7*fluctuation), currentPrice7+(currentPrice7*fluctuation));
setInterval(setRandomToElements, 5000);
}
</script>
Fiddle

Prototype issue - How do I check for links on an input field and check for the length of that input field?

I sort of started coding for this. It's almost working.
My goals:
1) Check for the length or url's entered in a field (the total length) and reduce each link's length by 20 if the length is greater than 20
2) Determine the characters left in an input field
The javascript in profile.js (prototype):
function checkurl_total_length(text) {
var text = "";
var matches = [];
var total_length = 0;
var urlRegex = /(http|https):\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/;
text.scan(urlRegex, function(match){ matches.push(match[0])});
for (var index = 0; index < matches.length; ++index) {
item = matches[index];
reduce_length = matches.length*20;
if(item.length>20) {
total_length = total_length + item.length - reduce_length;
}
else {
total_length = total_length + item.length;
}
}
return total_length;
}
function count_characters(field){
var limitNum=140;
var link_length = 0;
if(checkurl_total_length(field.value)!=0) {
link_length =link_length+ checkurl_total_length(field.value);
}
else {
link_length = 0;
}
limitNum = limitNum+link_length;
if( link_length !=0 ){
$("links").update("with links");
}
left = limitNum-field.value.length;
$("count").update(left);
}
THE HTML
<!DOCTYPE HTML>
<html lang="en"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>JUST A TEST FILE</title>
<script src="prototype.js" type="text/javascript"></script>
<script src="profile.js" type="text/javascript"></script>
</head><body>
<h1>
CHARACTERS COUNT
</h1>
<div class="container_24">
<h2 id="title2">
TESTING
</h2>
<div class="grid_24">
<div id="count"></div>
<br /s>
<div id="links"></div>
<form >
<textarea wrap="hard" onpaste="count_characters(this);" onkeyup="count_characters(this);" onkeydown="count_characters(this);" id="updates" onfocus="count_characters(this);" name="test"/> </textarea>
<input type="submit" value=" " name="commit" disabled=""/>
</form>
</div>
</div>
<!-- end .container_24 -->
</body></html>
Counting characters left is working but checking for url and the length of the url isn't. Any hints on why this isn't working?
not sure, but should this be
checkurl_total_length(field.value!=0) // ) != 0

Categories