Code, going through an array in javascript - javascript

'm trying to create a function that will continuously loop through an array and check if there are still elements with a certain value. If there are no more of these elements, then I would like the function to execute a certain action.
I'm checking for '0'. If nothing is ='0', then i want to display an image. Here's what I have, any suggestions?
function partiewin()
// On verifie si il y a encore des cases avec pour valeur '0' et si non, on fini la partie
{
var found=false;
for (i=1; i <= hauteur; i++)
{
for (j=1;j <= largeur; j++)
{
if( decor[i][j]!=0)
{
window.alert("You win");
found=1;
}
}
}
if(!found)
{
}
}
This is the array
var decor = new Array(hauteur);
for (i=0; i <= hauteur; i=i+1)
{
decor[i] = new Array(largeur);
}
The array is a long list of this shape :
decor[1][1] = '24'; decor[1][2] = '21'; decor[4][8]='0' ; etc
Shouldn't this work? I'm not getting any alerts or any answer whatsoever once all the '0' are technically gone from the map..

var found = false;
for(var i = 0; i < hauteur.length ; i++){
for (var j = 0; j< hauteur[i].length ; j++){
if( hauteur[i][j] == '0'){
found = true;
break;
}
}
}
if(!found){
console.log("display image code here")
}

Related

multiple select js when click on single element raise also checkall

I'm using this multiple checkbox plugin
http://multiple-select.wenzhixin.net.cn/docs/en/download
I'm using the filtering option
The problem that I have is that if I have only one option whit Select All like this image
when I click on BERMUDA option, in debug raises both
onClick event and onCheckAll event even if I don't click on Select All.
This thing happens only if I only have one entry besides "Select All" entry.
The js code is the following:
$("#" +ddl_ID).multipleSelect({
filter: true,
multiple: true,
"data-multiple-width": 150,
onClick: function (view) {
//aggiungo alla lista di selezionati solo il valore selezionato.
//se esiste già lo elimino
listaSel = $("#"+txtSel_ID).val();
var array = listaSel.replace("[", "").replace("]", "").split(",");
const index = array.indexOf(view.value);
if (index >= 0) //esiste già, lo elimino
array.splice(index, 1);
else //non esiste, lo aggiungo
array.push(view.value);
listaSel = "";
//ricostruisco la stringa
for (var i = 0; i < array.length; i++) {
if (array[i] != "")
listaSel += array[i] + ",";
}
if (listaSel.length > 0)
listaSel = listaSel.substring(0, listaSel.length - 1);
$("#" +txtSel_ID).val("[" + listaSel + "]");
console.log($("#" +txtSel_ID).val());
},
onCheckAll: function (view) {
listaSel = $("#" +txtSel_ID).val(); //attualmente nella ricerca
var listaSelezionata = $("#" +ddl_ID).multipleSelect("getSelects"); //selezionati adesso
var array = listaSel.replace("[", "").replace("]", "").split(",");
for (var i = 0; i < listaSelezionata.length; i++) {
const index = array.indexOf(listaSelezionata[i]);
if (index == -1) //non esiste, lo aggiungo
array.push(listaSelezionata[i]);
}
listaSel = "";
//ricostruisco la stringa
for (var i = 0; i < array.length; i++) {
if (array[i] != "")
listaSel += array[i] + ",";
}
if (listaSel.length > 0)
listaSel = listaSel.substring(0, listaSel.length - 1);
$("#" +txtSel_ID).val("[" + listaSel + "]");
console.log($("#" +txtSel_ID).val());
},
onUncheckAll: function (view) {
listaSel = $("#" +txtSel_ID).val(); //attualmente nella ricerca
var listaSelezionata = $("#" +ddl_ID).find('option').not(':selected'); //selezionati adesso
var array = listaSel.replace("[", "").replace("]", "").split(",");
for (var i = 0; i < listaSelezionata.length; i++) {
const index = array.indexOf(listaSelezionata[i].value);
if (index > -1) // esiste, lo rimuovo
array.splice(index, 1);
}
listaSel = "";
//ricostruisco la stringa
for (var i = 0; i < array.length; i++) {
if (array[i] != "")
listaSel += array[i] + ",";
}
if (listaSel.length > 0)
listaSel = listaSel.substring(0, listaSel.length - 1);
$("#" +txtSel_ID).val("[" + listaSel + "]");
console.log($("#" +txtSel_ID).val());
}
});
//se la listaSel è vuota richiamo per sicurezza l'uncheckall
if (listaSel == undefined || listaSel == "" || listaSel == "[]") {
console.log("lista null");
$("#" +ddl_ID).multipleSelect("uncheckAll");
}
//se no imposto i valori selezionati
else {
$("#" +ddl_ID).multipleSelect("setSelects", JSON.parse(listaSel));
}
}
Can someone help me?
Feels like its the plugin's default behavior but we can tackle it by simply looking at your question as the answer resides there. You mentioned that this issue occurs when only one item left in the multi-select box right? well, that's our cue.
So all you need to do is to place a condition to handle this issue when the length is only equal to one. Judging by your code, I believe we can get the total length by this line of code:
var listaSelezionata = $("#" +ddl_ID).multipleSelect("getSelects"); //selezionati adesso
And we will simply go into onCheckAll event and add a condition that if items are greater than 1 then only perform certain action in oncheckAll event else nothing will happen.
onCheckAll: function (view) {
var listaSelezionata = $("#" +ddl_ID).multipleSelect("getSelects"); //selezionati
if(listaSelezionata.length > 1){
//Do somthing
}
}
Hope it helps :)
Ciao Martina, tutto bene?
I have to admit I don't know the plugin you're using, but reading your question it seems it is a works as intended or side effect of the plugin itself.
To be sure about that you can try to see if an onUncheckAll event is fired when you uncheck BERMUDA and/or to repeat the same test with a search having two results and checking what happens when you select/unselect all the results.
If that is the case I simply suggest you to write your handles keeping in mind this behavior of the plugin.
Hope this helps.

New line in an output tag in JavaScript

I'm trying to show a pyramid of stars in an output tag and I can't get a new line to appear after every row? The output tag has id "result" and i can get the error messages to work if a user doesnt insert a number.
function teken(){
var resultaat =document.getElementById("result");
document.getElementById("result").innerText = "";
if(isNaN(getal.value)){
document.getElementById("result").innerText = "Een GETAL als ingave aub";
} else if(getal.value>10 || getal.value<2){
document.getElementById("result").innerText = "Getal moet groter dan 2 en kleiner dan 10 zijn"
} else {
for(var i = 1; i<= getal.value; i++){
for(var j = 1 ; j<=i;j++){
resultaat.value += "*";
}
resultaat.innerHTML += "<br>"
}
}
Thanks in advance!
Per my comment above, I think you just need resultaat.innerHTML += "*" instead of .value. Here's a trimmed down version of your code (with that edit) that works:
var resultaat = document.getElementById("result");
var n = 5;
for (var i = 1; i <= n; i++) {
for (var j = 1; j <= i; j++) {
resultaat.innerHTML += "*";
}
resultaat.innerHTML += "<br>"
}
<div id="result"></div>

javascript split and for functions

hi im trying to show multiple images with split ans for functios but im having problems:
the php returns a string with links separated by comas and i need to show as image each record this is the code:
var msg 'files/uploads/1688482n.jpg,files/uploads/10904912__n.jpg,files/uploads/10907098_0_o.jpg';
var img = explode(msg)
$('.mensage').html(img);//A el div con la clase msg, le insertamos el mensaje en formato thml
$('.mensage').show('slow');//Mostramos el div.
$("#im").val(""+msg+"");
}
function explode(t) {
var txt = t,
list = txt.split(","),
tt = "";
console.log(list);
for (var i = 0; i < list.length; i++) {
(tt += ("<img style='width:290px;height:190px;' class='img-tm2' src='"+i+"'><br>")); //This gets its place
}
return tt
}
in return im having this in the console:
Resource interpreted as Image but transferred with MIME type text/html:
so how i can display each image right?
the problem is showing like this:
<img style="width:290px;height:190px;" class="img-tm2" src="0">
<img style="width:290px;height:190px;" class="img-tm2" src="1">
Your code has a few bugs. Here is a corrected code:
var msg = 'n.jpg,o.jpg';
var img = explode(msg);
$('.mensage').val(img);//A el div con la clase msg, le insertamos el mensaje en formato thml
$('.mensage').show('slow');//Mostramos el div.
$("#im").html(img);
function explode(txt) {
var list = txt.split(",");
tt = "";
console.log(list);
for (var i = 0; i < list.length; i++) {
tt += "<img style='width:290px;height:190px;' class='img-tm2' src='"+list[i]+"'><br />"; //This gets its place
}
return tt;
}
Trying to enumerate them:
missing semicolons at the end of statements;
var msg = (missing "=");
i instead of list[i];
Why do you print i and not that ?
for (var i = 0; i < list.length; i++) {
(tt += ("<img style='width:290px;height:190px;' class='img-tm2' src='"+list[i]+"'><br>")); //This gets its place
}
use for each instead of for loop.
for each(var url in list) {
(tt += ("<img style='width:290px;height:190px;' class='img-tm2' src='"+url+"'><br>")); //This gets its place
}
return tt
}

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/']");

Javascript function returning fixed value from array

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 ) {
//...

Categories

Resources