console img
const num1Element = document.querySelector("#num1");
const num2Element = document.querySelector("#num2");
const resultElement = document.querySelector("#result");
const operatorlememt = document.querySelectorAll("[data-operation]")
function summary() {
if (operatorElememt == "+") {
const sumElement = Number(num1.value) + Number(num2.value);
resultElement.innerHTML = sumElement;
}
}
function multi() {
if (operatorElememt == "*") {
const multiElement = Number(num1.value) * Number(num2.value);
resultElement.innerHTML = multiElement;
}
}
function divide() {
if (operatorElememt == "/") {
const divideElement = Number(num1.value) / Number(num2.value);
resultElement.innerHTML = divideElement;
}
}
function subtraction() {
if (operatorElememt == "-") {
const subtractionElement = Number(num1.value) - Number(num2.value);
resultElement.innerHTML = subtractionElement;
}
}
<div class="container"></div>
<input class="num1" type="text">
<select name="" id="operator" class="operator">
<option data-operation value="-">-</option>
<option data-operation value="+">+</option>
<option data-operation value="/">/</option>
<option data-operation value="*">*</option>
</select>
<input class="num2" type="text">
<button onclick="summary();divide();multi();subtraction()">Click</button>
<br>
<span class="result_con">
<label for="" id="result"></label>
</span>
Console doesn't give any error code or any other result and I am quite new in to the subject. I was expecting a result regarding the selected operation. To select the operation I wrote select section and added the operations. I inteed to keep select part. Thanks in advance
I understand that you are a beginner. There were quiet a few issues with your code. I am attaching the snippet of the changes I made (I wouldn't consider myself an expert either and still may have overlooked something)
<body>
<div class="container"></div>
<input id="num1" type="text">
<select name="" id="operator" class="operator">
<option data-operation value="-">-</option>
<option data-operation value="+">+</option>
<option data-operation value="/">/</option>
<option data-operation value="*">*</option>
</select>
<input id="num2" type="text">
<button onclick="summary();divide();multi();subtraction()">Click</button>
<br>
<span class="result_con">
<label for="" id="result"></label>
</span>
<script>
const num1Element = document.querySelector("#num1");
const num2Element = document.querySelector("#num2");
const resultElement = document.querySelector("#result");
const operatorElememt = document.querySelector("#operator")
function summary() {
if (operatorElememt.value == "+") {
console.log("Adding");
const sumElement = Number(num1Element.value) + Number(num2Element.value);
resultElement.innerHTML = sumElement;
}
}
function multi() {
if (operatorElememt.value == "*") {
const multiElement = Number(num1Element.value) * Number(num2Element.value);
resultElement.innerHTML = multiElement;
}
}
function divide() {
if (operatorElememt.value == "/") {
const divideElement = Number(num1Element.value) / Number(num2Element.value);
resultElement.innerHTML = divideElement;
}
}
function subtraction() {
if (operatorElememt.value == "-") {
const subtractionElement = Number(num1Element.value) - Number(num2Element.value);
resultElement.innerHTML = subtractionElement;
}
}
</script>
</body>
Here are the issues I found:
You are trying to access your input element using a CSS selector for ids but you did not give those elements an id attribute
The select element works like an input element except it has a dropdown and limited options. You just need to get the select element like you would get an input Element. This also includes calling operatorElement.value
You are missing an E when getting the select element :)
And I would suggest instead of different functions, nest your conditions inside one event handler
Related
I'm newbie, I want to understand.
Cant output shipping-cost value.
It seems like I'm doing everything right, but I'm not getting the result.
I will be very grateful for your help
Code:
<select class="form-select" name = "shipping" id="country" required>
<option value="">Choose...</option>
<option value="DPD">DPD</option>
<option value="DHL">DHL</option>
<option value="DHL Express">DHL Express</option>
</select>
</label>
<div class="result"></div>
<script type="text/javascript">
const selectElement = document.querySelector('.form-select');
selectElement.addEventListener('change', (event) => {
const result = document.querySelector('.result');
result.textContent = `You chose ${event.target.value}`;
});
</script>
<div class="shipping-cost"></div>
<script type="text/javascript">
const shippingCost = document.querySelector('.text-success');
const shippingCostDisplay = document.querySelector('.shipping-cost');
selectElement.addEventListener('change', (event) => {
const result = document.querySelector('.result');
result.textContent = `You chose ${event.target.value}`;
switch(event.target.value) {
case 'DPD':
shippingCost.textContent = '$5';
break;
case 'DHL':
shippingCost.textContent = '$10';
break;
case 'DHL Express':
shippingCost.textContent = '$15';
break;
default:
shippingCost.textContent = '$0';
}
shippingCostDisplay.innerHTML = shippingCost.textContent;
});
</script>
It seems like the line <div class="shipping-cost"></div> should be responsible for this, but, unfortunately, it does not perform any function
You are missing <div class="text-success"></div>.
M.Eriksson is correct with his question in the comment.
Why?
Because you are missing div with class text-success, but you are trying to set it's value in switch, hence javascript throughs an error (mentioned by David)
Here is a working example (refactored just a bit your code)
const selectElement = document.querySelector('.form-select');
const shippingCost = document.querySelector('.text-success');
const shippingCostDisplay = document.querySelector('.shipping-cost');
selectElement.addEventListener('change', (event) => {
const result = document.querySelector('.result');
result.textContent = `You chose ${event.target.value}`;
switch(event.target.value) {
case 'DPD':
shippingCost.textContent = '$5';
break;
case 'DHL':
shippingCost.textContent = '$10';
break;
case 'DHL Express':
shippingCost.textContent = '$15';
break;
default:
shippingCost.textContent = '$0';
}
shippingCostDisplay.innerHTML = shippingCost.textContent;
});
<form>
<select class="form-select" name = "shipping" id="country" required>
<option value="">Choose...</option>
<option value="DPD">DPD</option>
<option value="DHL">DHL</option>
<option value="DHL Express">DHL Express</option>
</select>
</form>
<div class="result"></div>
<div class="shipping-cost"></div>
<div class="text-success"></div>
I would refactor your task like this:
const selectElement = document.querySelector('.form-select');
const shippingCost = document.querySelector('.text-success');
const shippingCostDisplay = document.querySelector('.shipping-cost');
selectElement.addEventListener('change', (event) => {
const result = document.querySelector('.result');
result.textContent = `You chose ${event.target.value}`;
shippingCostDisplay.textContent = shippingCost.textContent = event.target.value;
});
<form>
<select class="form-select" name = "shipping" id="country" required>
<option value="$0">Choose...</option>
<option value="$5">DPD</option>
<option value="$10">DHL</option>
<option value="$15">DHL Express</option>
</select>
</form>
<div class="result"></div>
<div class="shipping-cost"></div>
<div class="text-success"></div>
I am doing a Javascript exercise in which two images have to be superimposed, (an airplane flying over a beach). In it I must stop and start the animation and also be able to select the speed of the animation.
The first two functions (start and stop), work correctly, but not change the speed, are the following:
var playa = undefined;
window.onload = function () {
playa = document.getElementById("playa");
}
function parar() {
playa.style.animationPlayState = "paused";
playa.style.MozAnimationPlayState = "paused";
playa.style.WebkitAnimationPlayState = "paused";
}
function seguir() {
playa.style.animationPlayState = "running";
playa.style.MozAnimationPlayState = "running";
playa.style.WebkitAnimationPlayState = "running";
}
function velocidad(t) {
var valor = t + "s";
alert (valor);
console.log(valor);
playa.style.animationDuration = valor;
playa.style.MozAnimationDuration = valor;
playa.style.WebkitAnimationDuration = valor;
console.log(playa.style);
}
I change the speeds with the following select:
<select name="vel">
<option selected="selected" onclick="velocidad(4)">Normal</option>
<option onclick="velocidad(10)">Muy lento</option>
<option onclick="velocidad(8)">Lento</option>
<option onclick="velocidad(2)">Rápido</option>
<option onclick="velocidad(1)">Muy Rápido</option>
And the start and stop:
<input type="button" name="stop" value="stop" onclick="parar()" />
<input type="button" name="play" value="play" onclick="seguir()" />
The problem is when I press any selectable option, the value is not modified and changes are not applied.
You can call your method on change of select option:
<select name="vel" onchange="velocidad()">
<option selected="selected" value=4>Normal</option>
<option value=10>Muy lento</option>
<option value=8>Lento</option>
<option value=2>Rápido</option>
<option value=1>Muy Rápido</option>
</select>
In your method get the value of selected option and use that value.
javascript code for method velocidad:
function velocidad() {
var e = document.getElementById("vel");
var t = e.options[e.selectedIndex].value
var valor = t + "s";
alert(valor);
console.log(valor);
playa.style.animationDuration = valor;
playa.style.MozAnimationDuration = valor;
playa.style.WebkitAnimationDuration = valor;
console.log(playa.style);
}
I've made a calculator that works, it's not the prettiest, but it works and that's good enough for me since I'm pretty much a beginner at coding.
The last thing I'm missing is a little text box that shows the process of the calculation. an example would be "3+4=7".
I really appreciate every bit of help I can get. If you need any extra code from my files or anything then please let me know.
function calc() {
var n1 = parseFloat(document.getElementById("n1").value);
var n2 = parseFloat(document.getElementById("n2").value);
var oper = document.getElementById("operators").value;
if(oper === "+")
{
document.getElementById("result").value = n1+n2;
}
if(oper === "-")
{
document.getElementById("result").value = n1-n2;
}
if(oper === "/")
{
document.getElementById("result").value = n1/n2;
}
if(oper === "*")
{
document.getElementById("result").value = n1*n2;
}
}
<input type="number" id="n1"/>
<input type="number" id="n2"/>
<select id="operators">
<option value="+">+</option>
<option value="-">-</option>
<option value="/">/</option>
<option value="*">*</option>
</select>
<button onclick="calc();">sum</button>
<input type="text" id="result">
that should allow you to explore a little more in the world of JavaScript
const in_N1 = document.getElementById('n1')
, in_N2 = document.getElementById('n2')
, Operator = document.getElementById("operators")
, btCalc = document.getElementById('bt-Calc')
, txtResult = document.getElementById('result')
btCalc.onclick=()=>
{
let Result = 0
switch (Operator.value) {
case '+':
Result = in_N1.valueAsNumber + in_N2.valueAsNumber
break;
case '-':
Result = in_N1.valueAsNumber - in_N2.valueAsNumber
break;
case '/':
Result = in_N1.valueAsNumber / in_N2.valueAsNumber
break;
case '*':
Result = in_N1.valueAsNumber * in_N2.valueAsNumber
break;
}
txtResult.appendChild( document.createTextNode(` ${in_N1.value} ${Operator.value} ${in_N2.value} = ${Result} \n`) )
}
<input type="number" id="n1" value="0"/>
<select id="operators">
<option value="+" selected>+</option>
<option value="-">-</option>
<option value="/">/</option>
<option value="*">*</option>
</select>
<input type="number" id="n2" value="0"/>
<button id="bt-Calc"> = </button>
<pre id="result"></pre>
You can do like this
function calc() {
var n1 = parseFloat(document.getElementById("n1").value);
var n2 = parseFloat(document.getElementById("n2").value);
var oper = document.getElementById("operators").value;
if(oper === "+")
{
document.getElementById("result").value = n1+n2;
}
else if(oper === "-")
{
document.getElementById("result").value = n1-n2;
}
else if(oper === "/")
{
document.getElementById("result").value = n1/n2;
}
else if(oper === "*")
{
document.getElementById("result").value = n1*n2;
}
document.getElementById("operation").value = n1 + oper + n2 + "=" + document.getElementById("result").value;
}
<input type="number" id="n1"/>
<input type="number" id="n2"/>
<select id="operators">
<option value="+">+</option>
<option value="-">-</option>
<option value="/">/</option>
<option value="*">*</option>
</select>
<button onclick="calc();">sum</button>
<input type="text" id="result">
<input type="text" id="operation">
I'm sorry that a few variables are in dutch, I could change it to English if necessary.
This script should calculate the fee of the textbox "kosten".
The fee is calculated by applying a percentage, this is made possible by selecting a number in the combobox.
For some reason, when clicking on the button "totaalfooi" to start the calculation and get a result, nothing happends..
Javascript code:
function berekenkosten() {
var inputkosten = document.getElementById('kosten');
var kosten = 0;
if (inputkosten.value != "") {
kosten = parseInt(inputkosten.value);
}
return kosten;
}
var procentfooi = new Array();
procentfooi["1"]=2;
procentfooi["2"]=2.5;
procentfooi["3"]=3;
procentfooi["4"]=3.5;
procentfooi["5"]=4;
function berekenfooi () {
var berekenfooi=0;
for(var i = 0;
i < procentfooi.length; i++) {
if(procentfooi[i].checked) {
berekenfooi=procentfooi[procentfooi[i].value];
break;
}
}
return berekenfooi;
}
function berekentotaal () {
var totaalfooi = (berekenfooi/100) * berekenkosten();
document.getElementById(totaalfooi).innerHTML = "Totale fooi bedraagt: $" + totaalfooi;
}
<div id="JSfee">Totale kosten <input type="text" id="kosten"> <br><br> Graad van tevredenheid op 5
<select>
<option value="1" >1</option>
<option value="2" >2</option>
<option value="3" >3</option>
<option value="4" >4</option>
<option value="5" >5</option>
</select>
<input type="button" value="bereken" onclick="berekentotaal()">
<br><br>
<div id="totaalfooi">
</div>
</div>
You had multiple syntax errors which are fixed in the example below.
You cannot have variables named the same as functions, these will overwrite each other.
You cannot treat a function variable as a value type, you have to invoke the function.
getElementById takes a string argument, you were passing "variables" that were unassigned.
You needed an ID on your select, to then choose it by. You were iterating over an array which was not bound to the DOM.
A few other modifications, this works in the snippet and if you copy it over, should work to fix your problems.
function berekenkosten() {
var inputkosten = document.getElementById('kosten');
var kosten = 0;
if (inputkosten.value != "") {
kosten = parseInt(inputkosten.value);
}
return kosten;
}
function berekenfooi () {
var procentfooi = document.getElementById("procentfooi");
var percentToReturn=procentfooi.options[procentfooi.selectedIndex].value;
console.log(percentToReturn + " with " + procentfooi.length);
return parseFloat(percentToReturn);
}
function berekentotaal () {
var totaalfooi = (berekenfooi()/100) * berekenkosten();
document.getElementById("totaalfooi").innerHTML = "Totale fooi bedraagt: $" + totaalfooi;
}
<div id="JSfee">Totale kosten <input type="text" id="kosten"> <br><br> Graad van tevredenheid op 5
<select id='procentfooi'>
<option value="1" >1</option>
<option value="2" >2</option>
<option value="3" >3</option>
<option value="4" >4</option>
<option value="5" >5</option>
</select>
<input type="button" value="bereken" onclick="berekentotaal()">
<br><br>
<div id="totaalfooi">
</div>
</div>
Snippet results:
Change your code to this
function berekenkosten() {
var inputkosten = document.getElementById('kosten');
var kosten = 0;
if (inputkosten.value != "") {
kosten = parseInt(inputkosten.value);
}
return kosten;
}
function berekenfooi() {
var berekenfooi = 0,
seloption = document.querySelector('#JSfee select'),
procentfooi = [2, 2.5, 3, 3.5, 4]
return procentfooi[seloption.selectedIndex];
}
function berekentotaal() {
var totaalfooi = (berekenfooi()/100) * berekenkosten();
document.getElementById('totaalfooi').innerHTML = "Totale fooi bedraagt: $" + totaalfooi;
}
You have some syntactical errors in your berekentotaal function, berekenfooi is a function not an object therefore must be called with () and getElementById requires an string to find the element. With this solution you don't need the values in the select so they could be written like this
<select>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
Skimming through your code, it seems that the problem lies in this line:
document.getElementById(totaalfooi).innerHTML = "Totale fooi bedraagt: $" + totaalfooi;
totaalfooi is a result of a calculation, so I guess you meant to pass the string:
document.getElementById('totaalfooi').innerHTML = "Totale fooi bedraagt: $" + totaalfooi;
Also, in this line:
var totaalfooi = (berekenfooi/100) * berekenkosten();
You're dividing berekenfooi by 100, but berekenfooi is a function you define earlier, not a value. So it should be:
var totaalfooi = (berekenfooi()/100) * berekenkosten();
I want to add +10% to a value if that value is selected , but before i can implement it i need to make it work properly , first of the page shouldn't refresh and when i add a value and then i want to change it to another i want the old value from the other textbox to subtract ... i tried with a simple if/else if / else statement but because of the first error it won't work and i even ain't sure that it is working right. Here is the code:
<!doctype html>
<html>
<head>
<title>lol</title>
<meta charset="utf-8">
</head>
<body>
<form action="">
<input type="text" id="hp">
<input type="text" id="ea">
<input type="text" id="ed">
<input type="text" id="pa">
<input type="text" id="pd">
<input type="text" id="sp">
<select>
<option value="hp">HP</option>
<option value="ea">EA</option>
<option value="ed">ED</option>
<option value="pa">PA</option>
<option value="pd">PD</option>
<option value="sp">SP</option>
</select>
<input type="submit" id="sub" onClick = "return at()">
</form>
<script type="text/javascript">
function at () {
var a = document.form.select.options,
i = document.form.select.selectedIndex,
ea = Number(document.form.ea.value),
ed = Number(document.form.ed.value),
hp = Number(document.form.hp.value),
pd = Number(document.form.pd.value),
pa = Number(document.form.pa.value),
sp = Number(document.form.sp.value),
eaS,edS,pdS,paS,spS,hpS = 0;
if(a[i].text === "hp"){
hpS = hp*0.1;
}else if(a[i].text === "ea"){
eaS = ea*0.1
}else if(a[i].text === "ed"){
edS = ed*0.1
}else if(a[i].text === "pa"){
paS = pa*0.1
}else if(a[i].text === "pd"){
pdS = pd*0.1
}else if(a[i].text === "sa"){
spS = sp*0.1
}
document.form.ea.value = eaS;
document.form.ed.value = edS;
document.form.hp.value = hpS;
document.form.pd.value = pdS;
document.form.pa.value = paS;
document.form.sp.value = spS;
return false;
}
</script>
</body>
</html>
Look at the JavaScript console
I am willing to bet it has the error that says something like. If you do not see the error, set up your console so it persists errors across page navigation.
Uncaught TypeError: Cannot read property 'select' of undefined
You are looking for an element with the name of form and one with the name of select, but your form/select has no name.
<form action="">
<select>
should be
<form name="form" action="">
<select name="select">
Ideally you would drop the document.name.name syntax and use getElementById. Put an id on the select and form and reference the inputs that way too. Also a switch statement would be your friend.
Your code could be written without if statements, just use look ups based on the selects value.
function at() {
var sel = document.getElementById("mySelect");
var val = sel.options[sel.options.selectedIndex].value;
var input = document.getElementById(val);
if (input) {
var val = input.value;
resetValues();
input.value = parseFloat(val) * .1;
}
}
function resetValues() {
var inputs = document.getElementById("myForm").getElementsByTagName("input");
for (var i=0;i<inputs.length;i++) {
var inp = inputs[i];
if (inp.type==="text") inp.value = 0;
}
}
JSFiddle - Running example
many changes needed :
<!doctype html>
<html>
<head>
<title>lol</title>
<meta charset="utf-8">
</head>
<body>
<form action="">
<input type="text" name="hp" id="hp">
<input type="text" name="ea" id="ea">
<input type="text" name="ed" id="ed">
<input type="text" name="pa" id="pa">
<input type="text" name="pd" id="pd">
<input type="text" name="sp" id="sp">
<select id="mySelect">
<option value="hp">HP</option>
<option value="ea">EA</option>
<option value="ed">ED</option>
<option value="pa">PA</option>
<option value="pd">PD</option>
<option value="sp">SP</option>
</select>
<input type="button" id="sub" value="Submit" onClick = "return at()">
</form>
<script type="text/javascript">
function at () {
var a = document.getElementById('mySelect').options,
i = document.getElementById('mySelect').selectedIndex,
ea = Number(document.forms[0].ea.value),
ed = Number(document.forms[0].ed.value),
hp = Number(document.forms[0].hp.value),
pd = Number(document.forms[0].pd.value),
pa = Number(document.forms[0].pa.value),
sp = Number(document.forms[0].sp.value),
eaS,edS,pdS,paS,spS,hpS = 0;
if(a[i].text === "HP"){
hpS = hp*0.1;
}
if(a[i].text === "EA"){
eaS = ea*0.1
}
if(a[i].text === "ED"){
edS = ed*0.1
}
if(a[i].text === "PA"){
paS = pa*0.1
}
if(a[i].text === "PD"){
pdS = pd*0.1
}
if(a[i].text === "SA"){
spS = sp*0.1
}
document.forms[0].ea.value = eaS;
document.forms[0].ed.value = edS;
document.forms[0].hp.value = hpS;
document.forms[0].pd.value = pdS;
document.forms[0].pa.value = paS;
document.forms[0].sp.value = spS;
return false;
}
</script>
</body>
</html>
Something like this
<form action="">
<input type="text" id="hp">
<input type="text" id="ea">
<input type="text" id="ed">
<input type="text" id="pa">
<input type="text" id="pd">
<input type="text" id="sp">
<select name="select">
<option value="hp">HP</option>
<option value="ea">EA</option>
<option value="ed">ED</option>
<option value="pa">PA</option>
<option value="pd">PD</option>
<option value="sp">SP</option>
</select>
<input type="button" id="sub" value="Submit">
</form>
var sub = document.getElementById("sub");
function at() {
var a = document.forms[0].select.options,
i = document.forms[0].select.selectedIndex,
ea = Number(document.forms[0].ea.value),
ed = Number(document.forms[0].ed.value),
hp = Number(document.forms[0].hp.value),
pd = Number(document.forms[0].pd.value),
pa = Number(document.forms[0].pa.value),
sp = Number(document.forms[0].sp.value),
eaS, edS, pdS, paS, spS, hpS;
eaS = edS = pdS = paS = spS = hpS = 0;
if (a[i].text === "HP") {
hpS = hp * 0.1;
} else if (a[i].text === "EA") {
eaS = ea * 0.1
} else if (a[i].text === "ED") {
edS = ed * 0.1
} else if (a[i].text === "PA") {
paS = pa * 0.1
} else if (a[i].text === "PD") {
pdS = pd * 0.1
} else if (a[i].text === "SA") {
spS = sp * 0.1
}
document.forms[0].ea.value = eaS;
document.forms[0].ed.value = edS;
document.forms[0].hp.value = hpS;
document.forms[0].pd.value = pdS;
document.forms[0].pa.value = paS;
document.forms[0].sp.value = spS;
return false;
}
sub.addEventListener("click", at, false);
ob jsfiddle
I have not fixed every problem that you may have with your code, just the main part.And you can use this fiddle to work through your other problems.