innerHTML not printing anything - javascript

Im trying some stuff for an exam and I can't make it work. It's really simple and i can't understand why is not working.
<!DOCTYPE html>
<html>
<head>
<title>Exercici 2</title>
<script type="text/javascript">
//rep 2 paràmetres d'entrada i els suma
function suma(a, b) {
alert(arguments.length);
//donaria undefined, ja que no existeix el argument amb índex 2, tindria que ser [1]
alert(arguments[2]);
//3 + 5 = 8
return a + b;
}
var result = suma(3,5);
document.getElementById("result").innerHTML += "<strong>Suma</strong>: 3 + 5 = " + result + "<br>";
</script>
</head>
<body>
<div id="result">
</div>
</body>
</html>
I know alert(arguments[2]); will show undefined.

Issue is you are calling function before DOM is rendered. So result is not available. Move your script after body.
<html>
<head>
<title>Exercici 2</title>
</head>
<body>
<div id="result">
</div>
</body>
<script type="text/javascript">
//rep 2 paràmetres d'entrada i els suma
function suma(a, b) {
//3 + 5 = 8
return a + b;
}
var result = suma(3, 5);
document.getElementById("result").innerHTML += "<strong>Suma</strong>: 3 + 5 = " + result + "<br>";
</script>
</html>

Necesitas un onload para que funcione pues llamas el getElement By Id, antes de que exista el elemento y no tiene sentido. Ademas tu salida debe ser un string.
You need a "onload" function for this case, because you declare your getElemetnById before the element, also your output in your function should be a string.
<script type="text/javascript">
//rep 2 paràmetres d'entrada i els suma
function suma(a, b) {
//a = argumento 0, b = argumento 1
return (a + b).toString();
}
//estas ejecutando esto, sin antes existir el id="result", por tanto debes esperar
// aque primero se cree, y luego ejecutar, eso se hace añadiendo esto:
window.onload = function(){ //espera a que todos los elements html se creen.
var result = suma(3,5);
document.getElementById("result").innerHTML += "<strong>Suma</strong>: 3 + 5 = " + result + "<br>";
}
</script>

When working with Sums, it is advisable to add parseInt,
this way you can also add var result = suma('3', 5); and it will return 8, if you dont have the parseInt and you parse a string '3' it will concat it and will return 35
function suma(a, b) {
//3 + 5 = 8
return parseInt(a) + parseInt(b);
}
var result = suma(3, 5);
document.getElementById("result").innerHTML += "<strong>Suma</strong>: 3 + 5 = " + result + "<br>";

Related

Leaflet: resize bindPopup

How can I change the size of the bindPopup since when opening the web from a mobile phone it is very large, in the image that shows a lot of space is left below, is there any way to reduce that size?
search the internet but there are no results almost everything is from the bookmarks
This is part of the code I use to display this information:
const updateMap = () => {
const Buslocation =
"https:xxxxxxxxxxxxx" + gtebi;
fetch(Buslocation)
.then((res) => res.json())
.then((data) => {
//si existe el marcador removerlo para no tener marcadores duplicados
if (bus_marker) {
map.removeLayer(bus_marker);
}
//asignar valores que se usaran ingresar el marcador
const latitud = data.latitud;
const longitud = data.longitud;
//asignar valores que se usaran mas adelate para definir el popup
const destino = data.destino;
const origen = data.origen;
const patente = data.patente;
//animacion para dirigirse al punto donde se encuentra el bus
map.flyTo([latitud, longitud], 12);
//crear marcador
bus_marker = L.marker([latitud, longitud], {
icon: busicon,
})
.addTo(map)
.bindPopup(
"<strong><h3>El bus esta aquí</h3></strong>" +
"<h5>Origen: " +
"<strong>" +
origen +
"</strong>" +
"</h5>" +
"<h5>Destino: " +
"<strong>" +
destino +
"</strong>" +
"</h5>" +
"<h5>Patente: " +
"<strong>" +
patente +
"</strong>" +
"</h5>"
)
.update();
});
//definir el tiempo de actualizacion del marcador(bus)
setTimeout(updateMap, 180000);
};
I searched the internet but I only get options for the map markers.
or if I can remove the bindPopup somehow, because if I don't use it, the white bar is left next to it.

Why eventListener in JavaScript not displaying?

I have been struggling for hours with a simple addEventListener and I really don't understand why.
Find attached my JS code. I am trying to create a cart. I store in a localstorage the products I want to buy. Then I display it on a test page to see if my code was working.
I add a class to each line of the array using i variable.
Then I try to do a simple alert when I click on the link I created with the class. The goal is then to add a link to remove this article from the cart.
I get no error, but the alert does not display.
Plus, when I do
alert(querySelector('.article' + i + '').innerHTML);
it works perfectly, but with the code below it does not :
let url = window.location.search;
let searchUrl = new URLSearchParams(url);
if (searchUrl.has("produit")) {
//Requête fetch
fetch('http://localhost:3000/api/cameras')
.then(function(response) {
return response.json();
})
.then(function(produit) {
produit.forEach(element => {
// Récupération url, conversion string et mise en forme pour recherche
let urlProduit = String(searchUrl.getAll("produit"));
urlProduit = urlProduit.replace("-", " ");
//Affichage du produit
if (urlProduit == element.name) {
document.getElementById('content').innerHTML += '' + element.name + '';
document.getElementById('content').innerHTML += '<p>' + element.description + '</p>';
document.getElementById('content').innerHTML += '<p>' + element.price + '</p>';
document.getElementById('content').innerHTML += ' Ajouter au panier ';
// Gestion du panier
document.getElementById('ajoutPanier').addEventListener('click', function() {
if (localStorage.getItem("panier") == null) {
let panier = {};
panier.produits = [];
localStorage.setItem('panier', JSON.stringify(panier));
alert("Panier créé");
} else {
let panier = JSON.parse(localStorage.getItem("panier"));
panier.produits.push(element);
localStorage.setItem("panier", JSON.stringify(panier));
alert("Ajouté au panier");
}
});
}
})
})
}
//Affichage du panier
if (!localStorage.getItem("panier")) {
document.getElementById('panier').innerHTML += '<p> Votre panier est vide</p>';
}
else {
//Vider le panier
document.querySelector('#panier h2').innerHTML += ' (Vider) ';
document.querySelector('.viderPanier').addEventListener('click', function() {
alert("Panier vidé");
});
let i=0;
let panier = localStorage.getItem("panier");
panier = JSON.parse(panier);
console.log(panier); // A supprimer
panier.produits.forEach(element => {
document.getElementById('panier').innerHTML += '<p><strong>' + element.name + '</strong> - ' + element.price + ' € - Retirer du panier - Position' + i + ' </p>';
document.querySelector('.article' + i + '').addEventListener('click', function() {
console.log("ok");
alert("ok");
})
i++;
})
document.getElementById('panier').innerHTML += 'Passer la commande';
}
<!DOCTYPE html>
<html lang="fr" dir="ltr">
<head>
<meta charset="utf-8">
<title>Page produit</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="content">
Retour à l'acceuil<br>
<h2>Votre produit</h2>
</div>
<div id="panier">
<h2>Votre panier</h2>
</div>
<script src="produit.js" charset="utf-8"></script>
</body>
</html>
I just started JavaScript and eventListener perfectly worked so far. I know it is not the best solution for what I want to create, I am open to tips from you guys.

Call an url with parameters from jquery in mvc

I want to open a new url, pasing parameters using jquery, this is the way that im doing it,
$('#BtnPrintFlujo').click(function(e) {
var url = '#Url.Action("BillingxCashier", "Reports",new {area="Configurations" })';
url += "/opParam=" + $("#Users option:selected").val() +
"&fromDate=" + $('#FromDate').val() +
"&toDate=" + $('#ToDate').val();
var win = window.open(url);
if (win) {
win.focus();
} else {
alert("Porfavor, debes permitir que se abran las ventanas emergentes o el reporte no va a salir :'( ");
}
});
but, it said this error
Request.Path dangerous on the client (&).
$('#BtnPrintFlujo').click(function(e) {
var url = '#Url.Action("BillingxCashier", "Reports",new {area="Configurations" })';
url += "?opParam=" + $("#Users option:selected").val() +
"&fromDate=" + $('#FromDate').val() +
"&toDate=" + $('#ToDate').val();
var win = window.open(url);
if (win) {
win.focus();
} else {
alert("Porfavor, debes permitir que se abran las ventanas emergentes o el reporte no va a salir :'( ");
}
});
you missed an question mark before first parameter,
url += "?opParam=" + $("#Users option:selected").val() +
try this

Output in an array, and then show the array value for the user

My problem is that i need to store the value which appears whenever you click the 3 buttons. The code is supposed to let you have as many players as you want, and the players can "play" versus each other. And this "tool" counts whenever someone wins a round. However, i cant seem to find a way to save the output for every individual player, as it just stays the same whenever i change the player.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>title</title>
<script>
window.onload = oppstart;
var spiller1poeng = 0.0;
var spiller2poeng = 0.0;
function oppstart() {
var test = document.getElementById("knapp").onclick = spillere;
var poengspiller1 = document.getElementById("spiller1vant").onclick = plusspoengsplr1;
var dblelikt = document.getElementById("likt").onclick = beggelikt;
var poengspiller2 = document.getElementById("spiller2vant").onclick = plusspoengplr2;
}
function spillere() {
var x = document.getElementById("forstespiller").value;
var option = document.createElement("option");
option.innerHTML = x;
document.getElementById("spiller1nedtrekk").appendChild(option);
var z = document.getElementById("andrespiller").value;
var option2 = document.createElement("option");
option2.innerHTML = z;
document.getElementById("spiller2nedtrekk").appendChild(option2);
}
function plusspoengsplr1() {
var e = document.getElementById("spiller1nedtrekk");
spiller1poeng++ + 1;
var navnplayer1 = e.value;
document.getElementById("spiller1antall").innerHTML = navnplayer1 + " " + "har vunnet" + " " + spiller1poeng + " " + "runder.";
}
function beggelikt() {
var e = document.getElementById("spiller1nedtrekk");
var f = document.getElementById("spiller2nedtrekk");
var navnplayer1 = e.value;
var navnplayer2 = f.value;
spiller1poeng++ + 0.5;
spiller2poeng++ + 0.5;
document.getElementById("spiller1antall").innerHTML = navnplayer1 + " " + "har vunnet" + " " + spiller1poeng + " " + "runder.";
document.getElementById("spiller2antall").innerHTML = navnplayer2 + " " + "har vunnet" + " " + spiller2poeng + " " + "runder.";
}
function plusspoengplr2() {
var f = document.getElementById("spiller2nedtrekk");
var navnplayer2 = f.value;
spiller2poeng++ + 1;
document.getElementById("spiller2antall").innerHTML = navnplayer2 + " " + "har vunnet" + " " + spiller2poeng + " " + "runder.";
}
</script>
</head>
<body>
<h1>Turneringsverktøy</h1>
<h4>Step 1. Skriv inn et navn i hver av inputboksene, du kan ha så mange du vil men "Spiller 1" vil alltid spille mot "Spiller 2"</h4>
<h4>Step 2. Når du har skrevet inn et fint antall spillere i input-boksene (f.eks 4) velger du hvem som spiller mot hvem i nedtrekksboksene</h4>
<h4>NB! Man kan ikke velge nye spillere etter man har begynt å telle runder vunnet, skriv ned resultatet og refresh siden om nødvendig.</h4>
<input id="forstespiller" placeholder="Spiller 1">
<input id="andrespiller" placeholder="Spiller 2">
<br><br>
<select id="spiller1nedtrekk"></select>
<select id="spiller2nedtrekk"></select></select>
<br><br>
<button id="knapp">Legg til spillerene </button>
<p></p>
<br><br>
<button id="spiller1vant">Spiller 1 vant</button>
<button id="likt">Det ble likt</button>
<button id="spiller2vant">Spiller 2 vant</button>
<p id="spiller1antall">
</Spiller>
<p id="spiller2antall" </p>
</body>
</html>

Javascript : How access to a local function from global code

I have a function inside of an immediately invoked function expression and I want to be able to access that function globally without lexically scoping it that way.
How can I access this "private" function through a namespace called "App"?
indew.html:
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<script src="filtering.js"></script>
</head>
<body>
<article>
<p>
Computer graphics is widespread today. Computer imagery is found on televi
surfaces, illumination sources, and so forth, perhaps with a dynamic (time) component".[3]
</p>
</article>
<section id="result"></section>
<script>
App.showOccurenceFiltering(); // here is my wrong call
</script>
</body>
</html>
js script :
var App = (function () {
function showOccurenceFiltering() {
"use strict";
var filteredWordsArray = filtering(),
resultView = "<ol>";
for (var i = 0; i < filteredWordsArray.length; i++) {
var partWord = filteredWordsArray[i].substring(0, filteredWordsArray[i].indexOf(" ")), // de 0 jusqua l espace : la partie mot
partNumber = filteredWordsArray[i].substring(filteredWordsArray[i].indexOf(" ") + 1); // de l'espace à la fin : la partie number
resultView += "<li>" + partWord + " (" + partNumber + ")</li>";
}
resultView += "</ol>";
document.getElementById('result').innerHTML = resultView;
}
}(App));
so i got an error of a miss call like shows the capture :
how should i resolve my problem ??
You'll need to expose the function to the global scope. You can do this with a namespace, like this:
(function () {
function showOccurenceFiltering() {
"use strict";
var filteredWordsArray = filtering(),
resultView = "<ol>";
for (var i = 0; i < filteredWordsArray.length; i++) {
var partWord = filteredWordsArray[i].substring(0, filteredWordsArray[i].indexOf(" ")), // de 0 jusqua l espace : la partie mot
partNumber = filteredWordsArray[i].substring(filteredWordsArray[i].indexOf(" ") + 1); // de l'espace à la fin : la partie number
resultView += "<li>" + partWord + " (" + partNumber + ")</li>";
}
resultView += "</ol>";
document.getElementById('result').innerHTML = resultView;
}
// Prepare a "dummy" object
var obj = {};
// Attach the private function to this object
obj.showOccurenceFiltering = showOccurenceFiltering;
// Attach the dummy object to the global scope in a controlled namespace:
window.App = obj;
}());
Then you can access the function like this:
App.showOccurenceFiltering();
You could do the following:
var App = (function(){
var obj = {};
obj.showOccurenceFiltering = function() {
"use strict";
var filteredWordsArray = filtering(),
resultView = "<ol>";
for (var i = 0; i < filteredWordsArray.length; i++) {
var partWord = filteredWordsArray[i].substring(0, filteredWordsArray[i].indexOf(" ")), // de 0 jusqua l espace : la partie mot
partNumber = filteredWordsArray[i].substring(filteredWordsArray[i].indexOf(" ") + 1); // de l'espace à la fin : la partie number
resultView += "<li>" + partWord + " (" + partNumber + ")</li>";
}
resultView += "</ol>";
document.getElementById('result').innerHTML = resultView;
}
return obj;
}());
Your App variable remains undefined because the Immediately Invoked Function Expression does not return a value.
Instead, define App as an object literal, as follows:
var App = {
showOccurenceFiltering: function() {
"use strict";
var filteredWordsArray = filtering(),
resultView = "<ol>";
for (var i = 0; i < filteredWordsArray.length; i++) {
var partWord = filteredWordsArray[i].substring(0, filteredWordsArray[i].indexOf(" ")), // de 0 jusqua l espace : la partie mot
partNumber = filteredWordsArray[i].substring(filteredWordsArray[i].indexOf(" ") + 1); // de l'espace à la fin : la partie number
resultView += "<li>" + partWord + " (" + partNumber + ")</li>";
}
resultView += "</ol>";
document.getElementById('result').innerHTML = resultView;
}
};
Now your call will be valid.

Categories