JavaScript not found [object HTMLSpanElement], how i can fix that - javascript

"use strict";
let btn = document.getElementById("buttonCarrito");
btn.addEventListener("click",agregar);
//this function is agregar (add in English), the idea is that this function put the elements Manzana (Apple) in the shop cart but when i try do this i get [object HTMLSpanElement]50 (50 is the Apple value, but i don't can show only the number 50)
function agregar(){
let Productos= {
"Manzana": "50",
"Banana": "40",
"Naranja": "30",
"Mandarina": "20"
}
console.table(Productos)
let frutaComprada= document.getElementById("inputProducto").value;
let costoTotal= document.getElementById("valor");
let productoSeleccionado=Productos[frutaComprada];
costoTotal=costoTotal+productoSeleccionado;
valor.innerHTML=costoTotal;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="container">
<h1>Bienvenido a la tienda</h1>
<input id="inputProducto" type="text" placeholder="Ingrese su producto">
<br>
<br>
<input id="inputCompra" type="text" placeholder="Ingrese el valor de su compra">
<br>
<br>
<button id="buttonCarrito">Agregar al carrito</button>
<p>El valor total de su compra es: <span id="valor"> 0 </span></p>
</div>
</body>
<script src="js.js"></script>
</html>

Values from form inputs will always be strings, so to add numbers together you need to coerce the string to a number. A couple of methods: 1) Number(str) or 2) +str.
Your object of products/prices: there's no need to have those prices as strings.
The main problem you were having is that let costoTotal= document.getElementById("valor"); is only picking up the element and not the text content. We can use let costoTotal= document.getElementById("valor").textContent; for that, but then we need to coerce that to a number similarly to input values.
(Sidenote: at the moment your code doesn't use the value from inputCompra which is why I asked about it in the comments. So the total will increase by 40 for bananas, for example, regardless of what is entered in that input.)
let btn = document.getElementById("buttonCarrito");
btn.addEventListener("click", agregar);
function agregar() {
let Productos = {
Manzana: 50,
Banana: 40,
Naranja: 30,
Mandarina: 20
}
let frutaComprada = document.getElementById("inputProducto").value;
let costoTotal = Number(document.getElementById("valor").textContent);
let productoSeleccionado = Productos[frutaComprada];
costoTotal = costoTotal + productoSeleccionado;
valor.textContent = costoTotal;
}
<div class="container">
<h1>Bienvenido a la tienda</h1>
<input id="inputProducto" type="text" placeholder="Ingrese su producto">
<br>
<br>
<input id="inputCompra" type="text" placeholder="Ingrese el número de artículos">
<br>
<br>
<button id="buttonCarrito">Agregar al carrito</button>
<p>El valor total de su compra es: <span id="valor"> 0 </span></p>
</div>
Here's a version that uses quantity in case you were curious.
let Productos = {
Manzana: 50,
Banana: 40,
Naranja: 30,
Mandarina: 20
}
const product = document.getElementById('inputProducto');
const quantity = document.getElementById('inputCompra')
const valor = document.getElementById('valor');
const btn = document.getElementById('buttonCarrito');
btn.addEventListener('click', agregar);
function agregar() {
const frutaComprada = product.value;
const itemQuantity = Number(quantity.value);
const productoSeleccionado = Productos[frutaComprada];
const subTotal = productoSeleccionado * itemQuantity;
let costoTotal = Number(valor.textContent);
costoTotal = costoTotal + subTotal;
valor.textContent = costoTotal;
}
<div class="container">
<h1>Bienvenido a la tienda</h1>
<input id="inputProducto" type="text" placeholder="Ingrese su producto">
<br>
<br>
<input id="inputCompra" type="text" placeholder="Ingrese el valor de su compra">
<br>
<br>
<button id="buttonCarrito">Agregar al carrito</button>
<p>El valor total de su compra es: <span id="valor"> 0 </span></p>
</div>

Related

I can't see an alert advise

I’m studying how to work with HTML forms and JavaScript (JS) and I faced a problem:
I wrote the Meta tags (HTML) and used JS elements, events and functions to treat possible user mistakes. The page shows when user follow in mistake and don’t insert the correct information. But, even with these mistakes, when the “submit button” is used, the alert message is not showing. I tried to inspect what’s happening and browser give a message like:
“DevTools failed to load source map: Could not load content for chrome-extension://nllcnknpjnininklegdoijpljgdjkijc/bundles/content.js.map: System error: net::ERR_BLOCKED_BY_CLIENT”.
Here is my code:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2>HTML Forms</h2>
<form id="formulario" action="">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="">
<span id="msg-vld-fname" style="color: red; display:none;"></span>
<br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="">
<span id="msg-vld-lname" style="color: red; display:none;"></span>
<br><br>
<label for="lgenre">Genre:</label><br>
<select name="lgenre" id="lgenre">
<option value="select">Select</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<span id="msg-vld-lgenre" style="color: red; display:none;"></span>
<br><br>
<input type="submit" value="Submit">
</form>
<script src="./index.js"></script>
</body>
</html>
JavaScript
`
//selecionar elementos - aqui entra tudo o que vai ser "mexido", "manipulável"
let form = document.getElementById("formulario");
let fname = document.getElementById("fname");
let lname = document.getElementById("lname");
let lgenre = document.getElementById("lgenre");
let fname_msg = document.getElementById("msg-vld-fname");
let lname_msg = document.getElementById("msg-vld-lname");
let lgenre_msg = document.getElementById("msg-vld-lgenre");
//validar quando usuário sai do campo
fname.onblur = function (event) {
if (event.target.value.length < 3) {
fname_msg.textContent = "Insert at least 3 carachters"; //exibe a mensagem
fname_msg.style.display = 'block'; //exibe um valor na tela
} else {
fname_msg.style.display = 'none'; //faz o valor da tela "sumir".
}
}
//validar quando usuário muda um campo
lgenre.onchange = function (event) {
if (event.target.value == "select") {
lgenre_msg.textContent = "Select a valida atribute."; //exibe a mensagem
lgenre_msg.style.display = 'block'; //exibe um valor na tela
} else {
lgenre_msg.style.display = 'none'; //faz o valor da tela "sumir".
}
}
//validar quando usuário entra em um campo
fname.onfocus = function () {
fname_msg.style.display = 'none';
}
//validar quando usuário envia o formulário
form.onsubimit = function (event){
if (fname.value.length < 3
|| lgenre.value == "selecione") {
alert("please, complete this form correctly after submition");
event.preventDefault();
}
}
`
My expactation is: when the form has mistakes, according to the rules, shows the alert and forbiden the submitoin.
First, you wrote your event property incorrectly as: **onsubimit** instead of **onsubmit**.
But, you are using a submit button, which attempts to send the form data to whatever resource the form element's action attribute is set to and it will attempt to redirect the browser to that location. In your case, you're not submitting data anywhere, so you should be using a regular button with a click event handler.
Also, you really should be using the modern standard for setting up event handlers, which is .addEventListener() instead of event properties like onXyz. See the updated code for the button's click event below.
And the 6 heading elements in HTML (h1...h6) should not be used because of the way they style their text. They are for setting up the structure of the document. As such, you should always start with h1 and then only use h2 if you want to create a sub-section of the h1. If you then don't like the style of the text that the heading element produces, use CSS to modify that instead of changing to a heading style that you like to the look of.
//selecionar elementos - aqui entra tudo o que vai ser "mexido", "manipulável"
// You don't need a reference to the form, you need a reference to the button
let button = document.querySelector("input[type='button']");
let fname = document.getElementById("fname");
let lname = document.getElementById("lname");
let lgenre = document.getElementById("lgenre");
let fname_msg = document.getElementById("msg-vld-fname");
let lname_msg = document.getElementById("msg-vld-lname");
let lgenre_msg = document.getElementById("msg-vld-lgenre");
//validar quando usuário envia o formulário
// You should just use a regular button and set up a click event handler for it
// using the modern, standards-based approach of .addEventListener()
button.addEventListener("click", function (event){
if (fname.value.length < 3
|| lgenre.value == "selecione") {
alert("please, complete this form correctly after submition");
event.preventDefault();
}
});
//validar quando usuário sai do campo
fname.onblur = function (event) {
if (event.target.value.length < 3) {
fname_msg.textContent = "Insert at least 3 carachters"; //exibe a mensagem
fname_msg.style.display = 'block'; //exibe um valor na tela
} else {
fname_msg.style.display = 'none'; //faz o valor da tela "sumir".
}
}
//validar quando usuário muda um campo
lgenre.onchange = function (event) {
if (event.target.value == "select") {
lgenre_msg.textContent = "Select a valida atribute."; //exibe a mensagem
lgenre_msg.style.display = 'block'; //exibe um valor na tela
} else {
lgenre_msg.style.display = 'none'; //faz o valor da tela "sumir".
}
}
//validar quando usuário entra em um campo
fname.onfocus = function () {
fname_msg.style.display = 'none';
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>HTML Forms</h1>
<form id="formulario" action="">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="">
<span id="msg-vld-fname" style="color: red; display:none;"></span>
<br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="">
<span id="msg-vld-lname" style="color: red; display:none;"></span>
<br><br>
<label for="lgenre">Genre:</label><br>
<select name="lgenre" id="lgenre">
<option value="select">Select</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<span id="msg-vld-lgenre" style="color: red; display:none;"></span>
<br><br>
<input type="button" value="Submit">
</form>
<script src="./index.js"></script>
</body>
</html>

How to calculate the grade the person received

I'm doing my Homework but I need help calculating the right way, the code I provided is what I have so far, and this is what my teacher requires: Create a webpage that contains the heading, Student Grades, and inputs a student's homework average, mid-term exam score, final exam score, and participation (all those grades will be entered as integers). Create a script that checks for valid input, i.e., that the input is between 0-100 and that, of course, the input are all numbers. If all input is valid then calculate and display the student's final average sorry for dumb question i started learning JS not to long ago
const answer = () => {
let hwNum = document.querySelector('#hwAverage');
let mtNum = document.querySelector('#midTerm');
let feNum = document.querySelector('#finalExam');
let partiNum = document.querySelector('#participation');
let answer = document.querySelector('#result')
n1 = Number(hwNum);
n2 = Number(mtNum);
n3 = Number(feNum);
n4 = Number(partiNum);
let result = (.5 * n1) + (.2 * n2) + (.2 * n3) + (.1 * n4)
answer.textContent = result
return result
};
let submit = document.querySelector('#submit').addEventListener('click', function() { answer() } )
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="part1.css">
<script src="part1.js" defer></script>
<title>part 1</title>
</head>
<body>
<header>
<h1>Part 1</h1>
</header>
<br>
<label for="hwAvg"><b>Enter</b> Homework Average : </label>
<input type="number" name="hwAverage" id="hwAverage" placeholder="Enter Number 0-100">
<br>
<label for="term"><b>Enter</b> Mid-term exam score : </label>
<input type="number" name="midTerm" id="midTerm" placeholder="Enter Number 0-100">
<br>
<label for="exam"><b>Enter</b> Final exam score : </label>
<input type="number" name="finalExam" id="finalExam" placeholder="Enter Number 0-100">
<br>
<label for="partic"><b>Enter</b> Participation : </label>
<input type="number" name="participation" id="participation" placeholder="Enter Number 0-100">
<br>
<br>
<input type="button" value="SUBMIT" id="submit" class="submit">
<br>
<br>
<label for="resultLabel">Result : </label>
<div class="result" id="result"></div>
<br>
<br>
<div class="rubric">
<div class="A-tier">
<p>90-100 | A</p>
</div>
<div class="B-tier">
<p>80-89 | B</p>
</div>
<div class="C-tier">
<p>70-79 | C</p>
</div>
<div class="D-tier">
<p>60-69 | D</p>
</div>
<div class="F-tier">
<p>0-59 | F</p>
</div>
</div>
</body>
</html>**strong text**
Your solution is good.
If you want to get the data from a input element you have to use the value property.
Example:
let hwNum = document.querySelector('#hwAverage').value;
But if you want to get a element for manipulate you don't use the value property.
Example:
let answer = document.querySelector('#result');
Then if you want to set a data a input element you have to use the value property again. Example:
let hwNum = document.querySelector('#hwAverage');
hwNum.value = 'new value';
for anothers elements set value or data
let answer = document.querySelector('#result');
answer.textContent = 'new data o value';
You need to get the value of following input fields. Try this.
let hwNum = document.querySelector('#hwAverage').value;
let mtNum = document.querySelector('#midTerm').value;
let feNum = document.querySelector('#finalExam').value;
let partiNum = document.querySelector('#participation').value;
let answer = document.querySelector('#result').value;

Javascript: Avoid refreshing page after submit [duplicate]

This question already has answers here:
How do I make an HTML button not reload the page
(10 answers)
Closed 1 year ago.
my knowledge in Javascript is basic.
I'm trying to run a function when clicking the button submit, but when I do the page shows for a fraction of a second the result in the webpage but then it refreshes automatically showing the page in blank again. Any idea on how to fix this? Thanks in advance.
HTML
<section class="container-form">
<div>
<p>
Por favor ingresar los datos de tu préstamo para hacer el cálculo.
</p>
</div>
<form action="" id="form">
<input type="number" name="capital" id="capital" placeholder="Capital Inicial $">
<input type="number" name="rate" id="rate" placeholder="Tasa de Interés Anual %">
<input type="number" name="periods" id="periods" placeholder="Cantidad de cuotas">
<div>
<label for="frequency">Frecuencia de las cuotas</label>
<select name="frequency" id="frequency">
<option value="monthly">Mensual</option>
</select>
</div>
<div class="container-btn">
<input type="submit" id="btnSubmit" class="submit" onclick="calculateAnnuity()">
</div>
</form>
</section>
<section class="container-table">
<table id="table-results" class="table">
<thead>
<tr>
<th>Nº</th>
<th>Cuota</th>
<th>Interés</th>
<th>Capital</th>
<th>Saldo</th>
</tr>
</thead>
<tbody></tbody>
</table>
</section>
JS
// Declarar variables
let capital;
let rate;
let frequency;
let periods;
let btnSubmit;
let tableResults;
// Asignar valores a variables desde el form
capital = document.getElementById('capital');
rate = document.getElementById('rate');
frequency = document.getElementById('frequency');
periods = document.getElementById('periods');
btnSubmit = document.getElementById('btnSubmit');
tableResults = document.querySelector('#table-results tbody')
// Disparador de funcións
/* btnSubmit.addEventListener('click',() => {
calculateAnnuity(capital.value, rate.value, frequency.value, periods.value)
}) */
function calculateAnnuity (capital, rate, frequency, periods) {
// Declarar variables
let annuity = 0;
let actualCapital = capital;
let interestFee = 0;
let capitalFee = 0;
// Calculo de cuota
annuity = capital * (rate/100/12)
/
(1-Math.pow(1+rate/100/12,-periods));
console.log(typeof(capital)+" "+typeof(rate)+" "+typeof(periods)+" "+typeof(annuity))
for(let i = 0; i <= periods; i++) {
const row = document.createElement('tr');
row.innerHTML = `
<td>${i}</td>
<td>${parseFloat(annuity).toFixed(2)}</td>
<td>${parseFloat(interestFee).toFixed(2)}</td>
<td>${parseFloat(capitalFee).toFixed(2)}</td>
<td>${parseFloat(actualCapital).toFixed(2)}</td>
`
switch (frequency) {
case 'monthly':
interestFee = actualCapital * rate/100/12;
default:
continue;
}
capitalFee = annuity - interestFee;
actualCapital = actualCapital - capitalFee;
console.log(actualCapital);
tableResults.appendChild(row)
}
}
Form events comes with event or just e for intimates.
at your form action in javascript, you can use e.preventDefault(); function, to prevents browser to refresh when form is submited.

"Inspect" function (Ctrl + Shift + I) doesn't work

The "if (numero.value.length == 0)" works, but when I add a number the program doesn't work, the "Inspect" function (Ctrl + Shift + I) doesn't work and the page does not refresh.
function tabuada() {
var numero = document.getElementById('txtnum')
var tabuada = document.getElementById("selectTab")
if (numero.value.length == 0) {
window.alert("Você precisa digitar um número para que a tabuada seja gerada.")
} else {
var num = Number(numero.value)
tabuada.innerHTML = ""
for (c = 0; c = 10; c++) {
var item = document.createElement('option')
item.text = `${num} * ${c} = ${c * num}`
tabuada.appendChild(item)
}
}
}
<section>
<div>
<p>
Escolha um número: <input type="number" name="num" id="txtnum">
<input type="button" value="Gerar Tabuada" onclick="tabuada()">
</p>
</div>
<div>
<select name="tabuada" id="selectTab" size="10"></select>
</div>
</section>
You had to look more on your code:
Every opnening tag needs a closing one. /BODY and /HTML was missing.
Every line in Javascript needs a ; at the end.
The condition of your for-loop was wrong. You made an allocation c = 10 (which is allways true, so you have an infinite loop). If you want to compare something on equal use === or ==. But you had to compare for c < 10. The loop will as long iterate as your condition is true so smaller than is the choice.
Your function needs a closing }.
function tabuada() {
var numero = document.getElementById('txtnum');
var tabuada = document.getElementById("selectTab");
if (numero.value.length == 0) {
window.alert("Você precisa digitar um número para que a tabuada seja gerada.");
} else {
var num = Number(numero.value);
tabuada.innerHTML = "";
for (c = 0; c < 10; c++) {
var item = document.createElement('option');
item.text = `${num} * ${c} = ${c * num}`;
tabuada.appendChild(item);
}
}
}
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tabuada</title>
<link rel="stylesheet" href="_estiloEx16.css">
</head>
<body>
<header>
<h1>Tabuada</h1>
</header>
<section>
<div>
<p>
Escolha um número: <input type="number" name="num" id="txtnum">
<input type="button" value="Gerar Tabuada" onclick="tabuada()">
</p>
</div>
<div>
<select name="tabuada" id="selectTab" size="10"></select>
</div>
</section>
<footer>
<p>© Curso em vídeo</p>
</footer>
</body>
</html>

Problems with validating a document when trying to create a nested list using javascript

Here is my whole document. I'm having problems with the part in the head that starts with var tabNom1
and in the body after "Partie 2: Affichage du contenu HTML à partir de JavaScript" and before "Partie 3: Affichage et animation des images"
I am getting these errors:
Line 58, Column 28: document type does not allow element "ul" here
document.write("<ul>"); Line 58, Column 29: character data is not allowed here
document.write("<ul>"); Line 60, Column 29: character data is not allowed here
document.write("<ul>"); Line 62, Column 53: character data is not allowed here
{document.write("<li>" + tabNom1[x] + "</li>");}
In this document:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta content="fr-ca" http-equiv="Content-Language"/>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
<meta http-equiv="content-style-type" content="text/css"/>
<title>TP3</title>
<script type="text/javascript">
function addNumbers()
{
var val1 = parseInt(document.getElementById("Notetp1").value);
var val2 = parseInt(document.getElementById("Notetp2").value);
var val3 = parseInt(document.getElementById("Notetp3").value);
var val4 = parseInt(document.getElementById("Noteexamenintra").value);
var val5 = parseInt(document.getElementById("Noteexamenfinal").value);
var ansD = document.getElementById("Note finale");
ansD.value = val1 + val2 + val3 +val4 + val5;
}
var tabNom1 = {"Nom": "Smith", "Prenom": "John", "CodePermanent": "SMIT23325202", "Login": "Smith" };
</script>
<style type="text/css">
body {font-family:"Times New Roman", Times, serif;}
h2 {font-weight:bold;}
</style>
</head>
<body>
<h2>Partie 1: Formulaire du calcul de la note</h2>
Note tp1 : <input id="Notetp1" name="Note tp1" value="" type="text"/>
Note tp2 : <input id="Notetp2" name="Note tp2" value="" type="text"/>
Note tp3 : <input id="Notetp3" name="Note tp3" value="" type="text"/>
Note examen intra : <input id="Noteexamenintra" name="Note examen intra" value="" type="text"/>
Note examen final : <input id="Noteexamenfinal" name="Note examen final" value="" type="text"/>
<input name="Sumbit" value="Afficher la note finale" onclick="javascript:addNumbers()" type="button"/>
Note final : <input id="Notefinal" name="Note final" value="" type="text"/>
<h2>Partie 2: Affichage du contenu HTML à partir de JavaScript</h2>
<script type="text/javascript">
document.write("<ul>");
document.write("<li>" + "Equipier numéro 1:");
document.write("<ul>");
for (x in tabNom1)
{document.write("<li>" + tabNom1[x] + "</li>");}
document.write("</ul></li></ul>");
</script>
<h2>Partie 3: Affichage et animation des images</h2>
</body></html>
As noted to the answer to the first iteration of this question, update your body script as follows:
<script type="text/javascript">
//<![CDATA[
document.write("<ul>");
document.write("<li>" + "Equipier numéro 1:");
document.write("<ul>");
for (x in tabNom1)
{document.write("<li>" + tabNom1[x] + "<\/li>");}
document.write("<\/ul><\/li><\/ul>");
//]]>
</script>
That's adding CDATA and escaping the / in your closing elements.
See http://www.w3resource.com/javascript/document-alert-confirm/writing-text.php for examples.

Categories