Javascript function returning fixed value from array - javascript

I'm newbie with JavaScript, so I decided to develop a little application which is supposed to show the schedule of the streetcar of the place I live, because of the lack of the information on the official webpage.
I have several arrays with the starting time of the line, and as the time to reach each station it's the same, I only have to add the total minutes to the first hour.
There's a form for the user to set a range of hours. So, my main problem is that the "adder();" function is supposed to iterate and print all the values from an array. Instead of doing that, it takes always the same index, 24, so if the array returned has less than 24 indexes, it does not work.
Here's the HTML:
< input type="button" class="submit" value="Enviar" onclick="caller()"/>
JavaScript:
function cropHours(i){
if (i.substr(0,2) >= hora1user_recortada && i.substr(0,2) <= hora2user_recortada) {
horas.push(i);
}
return horas;
}
function adder() {
minInicio1 = horas[i].substr(0,2);
minInicio2 = horas[i].substr(3,2);
document.getElementById("test4").innerHTML = "---" + minInicio1+"_"+minInicio2;
y = parseInt(total) + parseInt(minInicio2);
document.getElementById("test5").innerHTML = "total vale "+total+"minInicio1 vale "+minInicio1+"... minInicio2 vale "+minInicio2+"...Y vale "+y;
html += "<td>"+y+"</td>";
document.getElementById("horario").innerHTML = html;
}
This is a part of another function:
if (platform == 1) {
for (var j = 0; j <= indexorigen; j++) {
total += mins1[j];
}
for (var j = 0; j <= indexdestino; j++) {
total2 += mins1[j];
}
if (today !== "Sábado" || today !== "Domingo") {
for each (var i in horainiciolaboral1) {
cropHours(i);
//adder(horainiciolaboral1);
}
} else {
for each (var i in horainiciofinde1) {
cropHours(i);
}
}
} else {
for (var x = 0; x <= indexorigen; x++) {
total += mins2[x];
}
for (var x = 0; x <= indexdestino; x++) {
total2 += mins2[x];
}
if (today !== "Sábado" || today !== "Domingo") {
for each (var i in horainiciolaboral2) {
cropHours(i);
}
} else {
for each (var i in horainiciofinde2) {
cropHours(i);
}
}
}
/*for (var i = 0; i <= horainiciolaboral1.length; i++) {
adder(horainiciolaboral1);
}*/
//horario = horas.slice(11);
for each (var i in horas) {
adder();
}
document.getElementById("test6").innerHTML = horas;
document.getElementById("test3").innerHTML = total + "----" + total2;
// ******************************************
// ** FUNCTION WHICH CALLS EVERY FUNCTION **
// ******************************************
// STARTS
function caller() {
cleaner();
retrieve_origen();
retrieve_destino();
getIndex();
sumMinutes();
getHours();
}
This is the problem:
for each (var i in horas) {
adder();
}
Thank you in advance.

Pass i to adder() as an argument:
adder(i);
...and define it as a parameter in the function:
function adder( i ) {
//...

Related

can't access value through input using button

I'm doing some exercises and come across where I can't pass the value from the input box to a function inside a script, I don't really know what I have done wrong, I tried different things but didn't really work out. How can I make it work? I want to able to enter a number then press a button so that it prints pyramid according to given number, here is my code :
window.onload = function() {
let aantalLijnen = parseInt(document.getElementById('number').value);
document.getElementById("button").onclick = stars();
function stars() {
for (var i = 1; i <= aantalLijnen; i++) {
var row = '';
for (var j = 1; j <= i; j++) {
row += '*';
}
console.log(row);
}
}
};
<p>Give a number betweeen 2 and 10
<input type="number" id='number'>
<button id="button">Click</button></p>
You're calling stars() and assigning the result to the onclick handler.
You need to pass the function itself...
document.getElementById("button").onclick = stars;
Or just create an anonymous function directly...
document.getElementById("button").onclick = function() {
...
}
As pointed out by #j08691, you are setting the value of aantalLijnen on the page load.
Instead you want to get the value at the time the function runs, so you need to move it into the function itself...
window.onload = function() {
document.getElementById("button").onclick = function () {
let aantalLijnen = parseInt(document.getElementById('number').value);
for (var i = 1; i <= aantalLijnen; i++) {
var row = '';
for (var j = 1; j <= i; j++) {
row += '*';
}
console.log(row);
}
}
};
<p>Give a number betweeen 2 and 10
<input type="number" id='number'>
<button id="button">Click</button></p>
you have to get the value from input every time you click on the button
window.onload = function () {
const numberElem = document.getElementById('number');
document.getElementById("button").addEventListener('click', stars);
function stars() {
let aantalLijnen = parseInt(numberElem.value);
for (var i = 1; i <= aantalLijnen; i++) {
var row = '';
for (var j = 1; j <= i; j++) {
row += '*';
}
console.log(row);
}
}
};
Besides what already said by others
Don't use onclick handlers. Stick to cumulative listeners with addEventListener
You could use String.prototype.repeat();
Defer your script or place it right before the closing </body> tag
Learn the difference between let and const
function stars() {
const num = parseInt(document.getElementById('number').value, 10);
if (num < 2 || num > 10) return console.log("Use from 2 to 10 inclusive");
const row = '*'.repeat(num);
console.log(row)
}
document.getElementById("button").addEventListener('click', stars);
Give a number betweeen 2 and 10
<input type="number" id='number'>
<button id="button">Click</button>

How to keep duplicates from being added to an array

var reservations = [];
function addReservation() {
//Gets Input from textboxes.
var nameChosen = document.getElementById("txtName").value;
var roomChosen = document.getElementById("selRoom").value;
//adds input into the array.
reservations[reservations.length] = roomChosen + " ";
reservations[reservations.length] = nameChosen + " ";
//Gets input from radio button.
for (i = 0; i < document.getElementsByName("Day[]").length; i++) {
if (document.getElementsByName("Day[]")[i].checked) {
reservations.push(document.getElementsByName("Day[]")[i].value);
}
}
for (i = 0; i < document.getElementsByName("Time[]").length; i++) {
if (document.getElementsByName("Time[]")[i].checked) {
reservations.push(document.getElementsByName("Time[]")[i].value);
}
}
}
How do I ensure that if the time and day cannot be added twice to the array?
Or easier yet, How do I ensure that the same name cannot be added twice to the array?
Test if the item is in the array first
if (!item in array) { array.push(item); }
I think that you are looking for a way to break out of the for loop after you hit the first match. One way to do this is to set i to the termination condition inside the if statement, which will exit the loop.
//Gets input from radio button.
for (i = 0; i < document.getElementsByName("Day[]").length; i++) {
if (document.getElementsByName("Day[]")[i].checked) {
reservations.push(document.getElementsByName("Day[]")[i].value);
i = document.getElementsByName("Day[]").length
}
}
for (i = 0; i < document.getElementsByName("Time[]").length; i++) {
if (document.getElementsByName("Time[]")[i].checked) {
reservations.push(document.getElementsByName("Time[]")[i].value);
i = document.getElementsByName("Time[]").length
}
}

jQuery load function inside jQuery load function

So I'm trying to parse a large amount of data from another website trough JavaScript and jQuery and (I'm new to both) so the problem here is the function inside the 2nd jQuery load() is not working.
function load() {
var r = 0;
var cols = [4,5,8,9,10];
$('#Parser').load('url #tableID', function () {
var r = $('#Parser').find('label').length;
for (var i = 0; i < r; i++) {
$('#table').append('<tr id="'+i+'"></tr>')
for (var j = 0; j < cols.length; j++) {
$('#'+i).append('<td id="c'+i+j+'"></td>')
$('#c'+i+j).load('url #tableId\\:Row'+i+'\\:Col'+cols[j], function() {
$('#c'+i+j).html($('#c'+i+j).children().text());
});
}
}
$('#Parser').html('');
});
}
So if tested this on its own with static id's and it works
$('#test').load('url #tableId\\:Row1\\:Col1', function() {
$('#test').html($('#test').children().text());
});
I need to parse the code by column and row like this because the webpage where I'm getting the data from has the data I want scattered over the columns on the cols variable and I find how many rows the table has on the r variable
I don't know if it's a logic problem or just a misuse of the functions but I have been struggling the whole day and I needed help.
The main load() function is called when the page starts, and this outputs the whole element instead of only the text
var time =new Date().getTime();
var rc = 0;
load();
refresh();
function load() {
var r = 0;
var cols = [4,5,8,9,10];
$('#Parser').load('url #tableID', function () {
var r = $('#Parser').find('label').length;
if (r != 0) {
//Simulating going back to this page
$('body').css({'background-color':'red','color':'white'});
for (var i = 0; i < r; i++) {
if (rc < r) {
$('#table').append('<tr id="'+i+'"></tr>')
}
for (var j = 0; j < cols.length; j++) {
if (rc < r) {
$('#'+i).append('<td id="c'+i+j+'"></td>')
}
col = $('#c'+i+j).load('url #tableId\\:Row'+i+'\\:Col'+cols[j],function() {
if ($('#c'+i+j).html != col){
$('#c'+i+j).html('');
}
});
}
}
}else {
if (rc != 0 ) {
for (var i = 0; i < rc; i++) {
for (var j = 0; j < cols.length ; j++) {
$('#c'+i+j).html('');
}
}
}
if ($('body').css('background-color') != 'white') {
//Simulating another page
$('body').css({'background-color':'white','color':'black'});
}
}
$('#Parser').html('');
if (rc < r) {
rc = r ;
}
});
}
function refresh() {
if(new Date().getTime() - time >= 10000){
load();
setTimeout(refresh, 10000);
}else{
setTimeout(refresh, 10000);
}
}
This is my full javascript on the page
the previous code is my atempt on processing it to text on a simpler way
Try this:
function load()
{
...your code...
}
$(document).ready(load);
Maybe the function is not being called on time, make sure you call it AFTER the DOM has been rendered.
Okay so it was a pretty easy fix, inside the second load function I have replaced
the
$('#c'+i+j).html($('#c'+i+j).children().text());
to
$(this).html($(this).text());
And it works fine now.

for loop failing to loop continuously

var _target=document.querySelectorAll('.post .content');
var isYT = /youtube|youtu.be/gi;
for (i = 0; i < _target.length; i++) {
var _tar = _target[i].children;
for (var j = 0; j < _tar.length; j++) {
var vidID;
if (_tar[j].tagName == "A") {
if (isYt.test(_tar[j].href) == true) {
_eles.push(_tar[j]);
}
}
if (_tar[j].tagName == "EMBED") {
if (isYt.test(_tar[j].src) == true) {
_eles.push(_tar[j]);
}
}
} //end for loop j
} //end for loop i
console.log(_eles);
The HTML looks sort of like this:
<div>
Video 1
Video 2
<embed src="www.youtube.com/v/239324"></embed>
</div>
<div>
Video 1
Video 2
<embed src="www.youtube.com/v/239324"></embed>
</div>
Though the returning array Object with my console logging is only showing one a element and one embed element. I have to continuously invoke this myself to get all the links and embeds to be placed into the array Object. Any one see any errors I've written, just been working on this issue for about 3 hours now and it is tiring me. Any help is greatly appreciated.
thank you
I have changed your code this way:
var _target = document.querySelectorAll("div");
var _eles = [];
var isYt=new RegExp("\youtube.com");
for (var i = 0; i < _target.length; i++) {
var _tar = _target[i].childNodes;
for (var j = 0; j < _tar.length; j++) {
var vidID;
if(_tar[j].nodeType != 1) continue;
if (_tar[j].tagName.toLowerCase() == "a") {
if (isYt.test(_tar[j].href)) {
_eles.push(_tar[j]);
}
}
if (_tar[j].tagName.toLowerCase() == "embed") {
if (isYt.test(_tar[j].src)) {
_eles.push(_tar[j]);
}
}
} //end for loop j
} //end for loop i
console.log(_eles);
and it works, check this DEMO
but my favorite way to do this is like this:
var _target = document.querySelectorAll("div>a, div>embed");
var _eles = [];
var isYt=new RegExp("\youtube.com");
for (var j = 0; j < _target.length; j++) {
var vidID;
if (_target[j].tagName.toLowerCase() == "a") {
if (isYt.test(_target[j].href)) {
_eles.push(_target[j]);
}
}
if (_target[j].tagName.toLowerCase() == "embed") {
if (isYt.test(_target[j].src)) {
_eles.push(_target[j]);
}
}
} //end for loop j
console.log(_eles);
for this check this one DEMO
and if your isYT regexp is just as simple as I have used in my answer instead of all these lines of code you can simply do:
var _eles = document.querySelectorAll("div>a[href*='youtube.com/'],"+
"div>embed[src*='youtube.com/']");

Populating multidimensional array

The code below came as an included file with a beginner puzzle app tutorial I'm working through. The code works, however now that I've completed the tutorial, I'm trying to read through the files that came preloaded which were not explained.
I'm really tripped up over the "spacecount" variable, and what exactly it's doing. Can anyone comment each line in plain english, so that I can better understand how exactly the code below is populating the rowCount array. Thank you so much.
var totalRows = puzzle.length;
var totalCols = puzzle[0].length;
/* Loop through the rows to create the rowCount array
containing the totals for each row in the puzzle */
var rowCount = [];
for (var i = 0; i < totalRows; i++) {
rowCount[i]="";
spaceCount = 0;
for (var j = 0; j < totalCols; j++) {
if (puzzle[i][j] == "#") {
spaceCount++;
if (j == totalCols-1) rowCount[i] += spaceCount + " ";
} else {
if (spaceCount > 0) {
rowCount[i] += spaceCount + " ";
spaceCount = 0;
}
}
}
Here's a slightly more legible version:
var totalRows = puzzle.length;
var totalCols = puzzle[0].length;
/* Loop through the rows to create the rowCount array
containing the totals for each row in the puzzle */
var rowCount = [];
for (var i = 0; i < totalRows; i++) {
rowCount[i] = "";
spaceCount = 0;
for (var j = 0; j < totalCols; j++) {
if (puzzle[i][j] == "#") {
spaceCount++;
if (j == totalCols - 1) {
rowCount[i] += spaceCount + " ";
}
} else if (spaceCount > 0) {
rowCount[i] += spaceCount + " ";
spaceCount = 0;
}
}
}​
The confusing parts are probably the if blocks in the middle.
if (puzzle[i][j] == "#") { // If a puzzle piece is `#` (a space?)
spaceCount++; // Increment the spaceCount by 1.
if (j == totalCols - 1) { // Only if we are on the last column, add the text
// to the row.
rowCount[i] += spaceCount + " ";
}
} else if (spaceCount > 0) { // If the current piece isn't a `#` but
// spaces have already been counted,
// add them to the row's text and reset `spaceCount`
rowCount[i] += spaceCount + " ";
spaceCount = 0;
}​
From what I can tell, this code counts the number of consecutive pound signs and appends this text to each row.

Categories

Resources