How to access the changed value of an onclick event? - javascript

I am a beginner in javascript and am doing an MMA score, I would like to know how I could access the changed value of result1Red.
<span><a id="result1Red">0</a></span>
which is changed by choosing one of the buttons that activates its respective function:
function tenRed1() {
var i = 10;
result1Red += 1*i;
if (result1Red > 10) {return;}
document.getElementById("result1Red").innerHTML = result1Red;
};
function nineRed1() {
var i = 9;
result1Red += 1*i;
if (result1Red > 10) {return;}
document.getElementById("result1Red").innerHTML = result1Red;
};
function eightRed1() {
var i = 8;
result1Red += 1*i;
if (result1Red > 10) {return;}
document.getElementById("result1Red").innerHTML = result1Red;
};
When I try with "innerHTML" it returns 0 (the initial value)
and not the determined value. I need this value to add up with the other inputs and get the total result.
Complete code:
// Round 1
function tenRed1() {
var i = 10;
result1Red += 1*i;
if (result1Red > 10) {return;}
document.getElementById("result1Red").innerHTML = result1Red;
};
function nineRed1() {
var i = 9;
result1Red += 1*i;
if (result1Red > 10) {return;}
document.getElementById("result1Red").innerHTML = result1Red;
};
function eightRed1() {
var i = 8;
result1Red += 1*i;
if (result1Red > 10) {return;}
document.getElementById("result1Red").innerHTML = result1Red;
};
function tenBlue1() {
var i = 10;
result1Blue += 1*i;
if (result1Blue > 10) {return;}
document.getElementById("result1Blue").innerHTML = result1Blue;
};
function nineBlue1() {
var i = 9;
result1Blue += 1*i;
if (result1Blue > 10) {return;}
document.getElementById("result1Blue").innerHTML = result1Blue;
};
function eightBlue1() {
var i = 8;
result1Blue += 1*i;
if (result1Blue > 10) {return;}
document.getElementById("result1Blue").innerHTML = result1Blue;
}
// Round 2
function tenRed2() {
var i = 10;
result2Red += 1*i;
if (result2Red > 10) {return;}
document.getElementById("result2Red").innerHTML = result2Red;
};
function nineRed2() {
var i = 9;
result2Red += 1*i;
if (result2Red > 10) {return;}
document.getElementById("result2Red").innerHTML = result2Red;
};
function eightRed2() {
var i = 8;
result2Red += 1*i;
if (result2Red > 10) {return;}
document.getElementById("result2Red").innerHTML = result2Red;
};
function tenBlue2() {
var i = 10;
result2Blue += 1*i;
if (result2Blue > 10) {return;}
document.getElementById("result2Blue").innerHTML = result2Blue;
};
function nineBlue2() {
var i = 9;
result2Blue += 1*i;
if (result2Blue > 10) {return;}
document.getElementById("result2Blue").innerHTML = result2Blue;
};
function eightBlue2() {
var i = 8;
result2Blue += 1*i;
if (result2Blue > 10) {return;}
document.getElementById("result2Blue").innerHTML = result2Blue;
};
// Round 3
function tenRed3() {
var i = 10;
result3Red += 1*i;
if (result3Red > 10) {return;}
document.getElementById("result3Red").innerHTML = result3Red;
};
function nineRed3() {
var i = 9;
result3Red += 1*i;
if (result3Red > 10) {return;}
document.getElementById("result3Red").innerHTML = result3Red;
};
function eightRed3() {
var i = 8;
result3Red += 1*i;
if (result3Red > 10) {return;}
document.getElementById("result3Red").innerHTML = result3Red;
};
function tenBlue3() {
var i = 10;
result3Blue += 1*i;
if (result3Blue > 10) {return;}
document.getElementById("result3Blue").innerHTML = result3Blue;
};
function nineBlue3() {
var i = 9;
result3Blue += 1*i;
if (result3Blue > 10) {return;}
document.getElementById("result3Blue").innerHTML = result3Blue;
};
function eightBlue3() {
var i = 8;
result3Blue += 1*i;
if (result3Blue> 10) {return;}
document.getElementById("result3Blue").innerHTML = result3Blue;
};
<html>
<head>
<title>MMAScore Beta</title>
<link rel="styleesheet" type="text/css" href="style/style.css">
</head>
<body>
<header>
<h1>mmaScore 0.1 Version</h1>
</header>
<!-- Round 1 -->
<div class="roundOne">
<button type="button" onclick="eightRed1()">8</button>
<button type="button" onclick="nineRed1()">9</button>
<button type="button" onclick="tenRed1()">10</button>
<span><a id="result1Red">0</a></span> -
<span><a id="result1Blue">0</a></span>
<button type="button" onclick="tenBlue1()">10</button>
<button type="button" onclick="nineBlue1()">9</button>
<button type="button" onclick="eightBlue1()">8</button>
</div>
<!-- Round 2 -->
<div class="roundTwo">
<button type="button" onclick="eightRed2()">8</button>
<button type="button" onclick="nineRed2()">9</button>
<button type="button" onclick="tenRed2()">10</button>
<span><a id="result2Red">0</a></span> -
<span><a id="result2Blue">0</a></span>
<button type="button" onclick="tenBlue2()">10</button>
<button type="button" onclick="nineBlue2()">9</button>
<button type="button" onclick="eightBlue2()">8</button>
</div>
<!-- Round 3 -->
<div class="roundThree">
<button type="button" onclick="eightRed3()">8</button>
<button type="button" onclick="nineRed3()">9</button>
<button type="button" onclick="tenRed3()">10</button>
<span><a id="result3Red">0</a></span> -
<span><a id="result3Blue">0</a></span>
<button type="button" onclick="tenBlue3()">10</button>
<button type="button" onclick="nineBlue3()">9</button>
<button type="button" onclick="eightBlue3()">8</button>
</div>
<h3>Total:</h3>
<span id="resultRed">0</span> -
<span id="resultBlue">0</span>
<footer>
</footer>
<script type="text/javascript" src="script/script.js"></script>
</body>
</html>

Regarding your code
First I would like to point a couple of issues with your code and give you some advice :
write <span> instead of <spam>
<a> tags are for links only you don't need to have <span><a>...</a></span>
try to use less ìds and class names
don't use .innerHTML if you're not planning on adding HTML, use .textContent instead
your JavaScript code is way too redundant: you've defined 18 similar functions! Functions need to be reusable.
A proposal
Here's how you could implement your process.
we will add an event listener to the document to listen to any clicks inside the page. We'll use addEventListener for that.
document.addEventListener('click', function() {})
As you can see it takes the event type ('click') and a callback function that it will execute when the event happens. We need to define this callback.
The callback needs to first check that the clicked item is indeed a button and it's parent (if he has any) has the class name: .round.
const parent = event.target.parentElement;
if (parent && parent.classList.contains('round')) {
...
}
If the condition is met then it means the user has clicked on one of the buttons.
In the if block we can start working with event.target which is the element that has been clicked (in our case it will be one of the <button> element). We will start by saving some variables: button (the <button> element), amount (the button's value) and team (the team: either 'Red' or 'Blue').
const button = event.target;
const amount = button.textContent;
const team = button.className.substr(3);
Then we will update the round's point:
parent.querySelector('.result'+team).textContent = amount;
And finally, update the total amount using updateTotals:
updateTotals('.result'+team);
Full code:
const updateTotals = function(className) {
const total = [...document.querySelectorAll('.round '+className)]
.map(e=> parseInt(e.textContent))
.reduce((a,b) => a+b);
document.querySelector('.results > '+className).textContent = total;
};
document.addEventListener('click', function() {
const parent = event.target.parentElement;
if (parent && parent.classList.contains('round')) { // this is a <button>
const button = event.target;
const amount = button.textContent;
const team = button.className.substr(3);
// update team score
parent.querySelector('.result'+team).textContent = amount;
// update total for each team
updateTotals('.result'+team);
}
});
<h1>mmaScore 0.1 Version</h1>
<!-- Round 1 -->
<div class="round round1">
<button class="btnRed" type="button">8</button>
<button class="btnRed" type="button">9</button>
<button class="btnRed" type="button">10</button>
<span class="resultRed">0</span> -
<span class="resultBlue">0</span>
<button class="btnBlue" type="button">10</button>
<button class="btnBlue" type="button">9</button>
<button class="btnBlue" type="button">8</button>
</div>
<!-- Round 2 -->
<div class="round round2">
<button class="btnRed" type="button">8</button>
<button class="btnRed" type="button">9</button>
<button class="btnRed" type="button">10</button>
<span class="resultRed">0</span> -
<span class="resultBlue">0</span>
<button class="btnBlue" type="button">10</button>
<button class="btnBlue" type="button">9</button>
<button class="btnBlue" type="button">8</button>
</div>
<!-- Round 3 -->
<div class="round round3">
<button class="btnRed" type="button">8</button>
<button class="btnRed" type="button">9</button>
<button class="btnRed" type="button">10</button>
<span class="resultRed">0</span> -
<span class="resultBlue">0</span>
<button class="btnBlue" type="button">10</button>
<button class="btnBlue" type="button">9</button>
<button class="btnBlue" type="button">8</button>
</div>
<h3>Total:</h3>
<div class="results">
<span class="resultRed">0</span> -
<span class="resultBlue">0</span>
</div>
About updateTotals:
The function allows to take the sum of all points for the specified team. It takes as argument className of type String which can either be 'resultRed' or 'resultBlue'.
Here's how it works:
it starts by selecting all of the point elements and spreading the selection returned by querySelectorAll into an array.
[...document.querySelectorAll('.round '+className)]
then we can map this array like so HTMLElement => Number using .map
.map(e=> parseInt(e.textContent))
then the resulting mapped array can be reduced to a single integer: the sum of all the elements of the array using a .reduce. Here's a Stack Overflow thread on How to find the sum of an array of numbers.
Finally change the team's total count in the DOM with the calculated sum total.
As a result we have:
const updateTotals = function(className) {
const total = [...document.querySelectorAll('.round '+className)]
.map(e=> parseInt(e.textContent))
.reduce((a,b) => a+b);
document.querySelector('.results > '+className).textContent = total;
};

Found post already has accepted answer and 4 upvotes when I finished this. I'm going to post it anyway, just for ref.
NodeList.prototype.map=Array.prototype.map;
const sum=()=>{
resultRed.innerText=document.querySelectorAll(".resultRed").map(x=>x.innerText).reduce((a,b)=>Number(a)+Number(b));
resultBlue.innerText=document.querySelectorAll(".resultBlue").map(x=>x.innerText).reduce((a,b)=>Number(a)+Number(b));
}
for(const cn of document.querySelectorAll("body>div").map(x=>x.className)){
const parent=document.getElementsByClassName(cn)[0];
parent.querySelectorAll("button").forEach((v,i)=>{
if(i<=2) v.onclick=()=>{
parent.querySelector(".resultRed").innerText=v.innerText;
sum();
}
else v.onclick=()=>{
parent.querySelector(".resultBlue").innerText=v.innerText;
sum();
}
});
}
<!-- Round 1 -->
<div class="roundOne">
<button type="button">8</button>
<button type="button">9</button>
<button type="button">10</button>
<spam><a class="resultRed">0</a></spam> -
<spam><a class="resultBlue">0</a></spam>
<button type="button">10</button>
<button type="button">9</button>
<button type="button">8</button>
</div>
<!-- Round 2 -->
<div class="roundTwo">
<button type="button">8</button>
<button type="button">9</button>
<button type="button">10</button>
<spam><a class="resultRed">0</a></spam> -
<spam><a class="resultBlue">0</a></spam>
<button type="button">10</button>
<button type="button">9</button>
<button type="button">8</button>
</div>
<!-- Round 3 -->
<div class="roundThree">
<button type="button">8</button>
<button type="button">9</button>
<button type="button">10</button>
<spam><a class="resultRed">0</a></spam> -
<spam><a class="resultBlue">0</a></spam>
<button type="button">10</button>
<button type="button">9</button>
<button type="button">8</button>
</div>
<h3>Total:</h3>
<spam id="resultRed">0</spam> -
<spam id="resultBlue">0</spam>
<footer>
</footer>

Related

How to do an event listener so that = sign calculates Sum?

My understanding of an event handler is that it allows the event handler that takes an existing function and allows you to do something with it like a click or some kind of event
What I am trying to do is when the = button is pressed on my calculator it uses the calculation function and takes the if-else statements and applies it to the = sign. For example, if the user clicks 1 + 1 the = sign should add them together and give the answer.
/*********************
Setting up varlaibles*
**********************/
let result;
let num1;
let num2;
/*****************************************
Function for numbers to display on screen*
******************************************/
function buttonPress(numbers) {
let input = document.querySelector('.answer').innerText.split('\n').join('') + numbers
let display = document.querySelector('.answer').innerHTML = input
console.log(`${typeof display} ${display}`)
if (display.length >= 21) {
for (let i = 0; i < display.length; i++) {
document.querySelector('.answer').style.marginTop = -i + "px";
}
}
}
/***********************************
Function for calculation of numbers*
************************************/
function calculation(buttonPress) {
switch (numbers) {
case "/":
numbers / numbers;
break;
case "*":
numbers * numbers;
break;
case "+":
numbers + numbers;
break;
case "-":
numbers - numbers;
break;
case "%":
numbers % numbers;
break;
default:
}
buttonPress()
}
<div class="answer"></div>
<div class="row">
<div class="col">
<button class="col-op clear" onclick="buttonPress('C')">C</button>
<button class="col-op" onclick="buttonPress('()')">()</button>
<button class="col-op" onclick="buttonPress('%')">%</button>
<button class="col-op" onclick="buttonPress('/')">/</button>
</div>
<div class="col">
<button class="col-num" onclick="buttonPress(1)">1</button>
<button class="col-num" onclick="buttonPress(2)">2</button>
<button class="col-num" onclick="buttonPress(3)">3</button>
<button class="col-op-end" onclick="buttonPress('X')">x</button>
</div>
<div class="col">
<button class="col-num" onclick="buttonPress(4)">4</button>
<button class="col-num" onclick="buttonPress(5)">5</button>
<button class="col-num" onclick="buttonPress(6)">6</button>
<button class="col-op-end" onclick="buttonPress('+')">+</button>
</div>
<div class="col">
<button class="col-num" onclick="buttonPress(7)">7</button>
<button class="col-num" onclick="buttonPress(8)">8</button>
<button class="col-num" onclick="buttonPress(9)">9</button>
<button class="col-op-end" onclick="buttonPress('-')">-</button>
</div>
<div class="col">
<button class="col-num" id="border-left" onclick="buttonPress(0)">0</button>
<button class="col-num" onclick="buttonPress('.')">.</button>
<button class="col-eq-end" id="border-right" onclick="buttonPress('=')">=</button>
</div>
</div>
The outcome should be with addEventListener that if the user uses operators to with the numbers the = sign should give the answer.
to add listener
element.addEventListener('eventName', callbackFunction(){})
to calculate using simple method
let result = eval("15 + 4 - 2 * 4")
console.log(result)
but they said eval() is evil so you can try method below
let char, result = '';
document.querySelectorAll('button').forEach(button=> { // add click event to all button
button.addEventListener('click', (e)=> {
char = e.target.textContent;
if (char == '=') {
// using eval()
// document.querySelector('.answer').textContent = eval(result)
//
let values = result.split(/([-+\/\*])/);
for (let i = 0; i < values.length; i++) {
if (isNaN(values[i])) {
let operator = values[i]
i++;
let nextNumber = parseFloat(values[i])
result = operations[operator](result, nextNumber)
} else {
result = parseFloat(values[i])
}
}
} else if (char == 'C') {
result = '';
} else {
result += char;
}
document.querySelector('.answer').textContent = result
})
})
var operations = {
'+': (a, b) => a + b,
'-': (a, b) => a - b,
'*': (a, b) => a * b,
'/': (a, b) => a / b,
};
.answer{display: block;width: 200px;height: 20px;border: 1px solid #bbb;margin: 10px 0;}
<div class="answer">0</div>
<div class="row">
<div class="col">
<button class="col-op clear">C</button>
<button class="col-op">()</button>
<button class="col-op">%</button>
<button class="col-op">/</button>
</div>
<div class="col">
<button class="col-num">1</button>
<button class="col-num">2</button>
<button class="col-num">3</button>
<button class="col-op-end">*</button>
</div>
<div class="col">
<button class="col-num">4</button>
<button class="col-num">5</button>
<button class="col-num">6</button>
<button class="col-op-end">+</button>
</div>
<div class="col">
<button class="col-num">7</button>
<button class="col-num">8</button>
<button class="col-num">9</button>
<button class="col-op-end">-</button>
</div>
<div class="col">
<button class="col-num" id="border-left">0</button>
<button class="col-num">.</button>
<button class="col-eq-end" id="border-right">=</button>
</div>
</div>

how to index inside onclick in javascript

I have simple 5 buttons like this:
<button class="btn btn-success">Button 1</button>
<button class="btn btn-success">Button 2</button>
<button class="btn btn-success">Button 3</button>
<button class="btn btn-success">Button 4</button>
<button class="btn btn-success">Button 5</button>
I have this corresponding javascript code:
document.addEventListener("DOMContentLoaded",function(){
var button = document.getElementsByClassName('btn');
for (var i = 0; i < button.length; i++) {
button[i].onclick = function(){
console.log("button " + i)
}
}
},false)
I want to index i for button array inside onclick, for purpose such as button[i].classList.add("something"), I don't want to use "this" like this.classList.add("something"). How can I do that?, thanks
try to
const buttons = document.querySelectorAll(".clickme");
var count = 0;
buttons.forEach(btn => {
btn.addEventListener("click", (e) => {
const index = Array.from(buttons).indexOf(e.target);
alert(index);
});
});
I found it on https://www.mejorcodigo.com/p/20019.html

Creating dynamic cards using jQuery

I'm doing an e-trade site with jQuery; however, when I increase then submit one of the products, they all get the properties of the first product. I defined the products as a json to a variable.
How can I create dynamic cards with jquery?
Here is how it looks:
İmage
Here is the source code:
$(document).on('click', '.number-spinner button', function() {
var btn = $(this),
oldValue = btn.closest('.number-spinner').find('input').val().trim(),
newVal = 0;
newVal = (btn.attr('data-dir') === 'up') ? parseInt(oldValue) + 1 : (oldValue > 1) ? parseInt(oldValue) - 1 : 0;
btn.closest('.number-spinner').find('input').val(newVal);
});
let html = data.reduce((acc, {name,value,image,counter,totalMoney}) =>
acc + `
<div class='card col-md-3'>
<img class='card-img-top' src="${image}" alt='Card image cap'>
<div class='card-body'>
<h5 class='card-title'>${name}</h5>
<p class="card-text">${value}</p>
<input class="money-input money" value="${value}"/>
<div class="number-spinner">
<div class="input-group number-spinner">
<span class="input-group-btn">
<button type="button" class="btn btn-default btn-number btn-minus" data-type="minus" data-dir="dwn"><span>-</span></button>
</span>
<input min="1" class="adet input-number" value="${counter}" type="number">
<span class="input-group-btn">
<button type="button" class="btn btn-default btn-number btn-plus" data-type="plus" data-dir="up"><span>+</span></button>
<div class="total-price"></div>
</span>
</div>
</div>
<button class="submit">Add To Card</button>
</div>
</div>`
, ``);
$('#list').append(html);
const adet = $(".adet").val()
const money = $(".money").val()
const totalMoney = adet * money;
var endText = 'Price'
var space = ' '
$( ".submit" ).click(function() {
$(".total-price").text($(".adet").val() * totalMoney);
$('.total-price').append( space + endText);
});
The "problem" is that you have (possibly) multiple elements with the class .adet and .money. However, the .val() method of a jQuery collection only extracts the value of the first element it contains. See the jQuery docs:
Get the current value of the first element in the set of matched elements...
jQuery docs

Dynamically add increment/decrement counter

I am trying to implement a dynamic increment/decrement counter. Here is how it should work:
I have an 'ADD' button. When i click on this, the same should disappear and a minus button, number input, plus button should appear. Clicking on "+" should increment the counter on the "cart" and clicking on "-" should decrement.
Below is html mycode
<body>
<div id="page-wrap">
<h1>Cart Inc Dec</h1>
<a href="#" class="btn btn-info btn-lg mt-5 mr-5 mb-5">
<span class="glyphicon glyphicon-shopping-cart"><span id="itemCount"></span></span> Check Out
</a>
<br>
<a id="btnAddItem" class="btn btn-primary float-right mt-5 mb-5 mr-5">ADD</a>
<div class="addItem">
</div>
</div>
</body>
Jquery:
<script>
var addElement = 0;
$(document).ready(function(){
$("#btnAddItem").on("click", function (event) {
if(addElement==0){
$(".addItem").append(('<button type="button" class="counter decrease">-</button><input type="text" size="5" id="txtCounter" /><button type="button" class="counter increase">+</button>'));
}
addElement++;
});
var $input = $("#txtCounter");
// Initialise the value to 0
$input.val(0);
debugger;
// Increment/decrement count
$(".counter").click(function(){
console.log('here i am');
if ($(this).hasClass('increase'))
$input.val(parseInt($input.val())+1);
else if ($input.val()>=1)
$input.val(parseInt($input.val())-1);
});
});
</script>
Now the problem is after i add the dynamic +, text input counter, - controls, nothing happens when i click on + or minus. console.log inside $(".counter").click(function() is not giving anything.
Am i missing something??
You can do it like this: Adjust the $(".counter").click(function() {}); to $(document).on("click", ".counter", function(){}); as the element with the class counter isn't there when the page is initially loaded and therefore the click() event has to be delegated from a static parent element to the added counter element using on(). Move then the variable declaration var $input = $("#txtCounter"); inside this click function as the element with the id txtCounter isn't there when the page is initally loaded and move the initialization $("#txtCounter").val(0); after appending it.
var addElement = 0;
$(document).ready(function() {
$("#btnAddItem").on("click", function(event) {
if (addElement == 0) {
$(".addItem").append(('<button type="button" class="counter decrease">-</button><input type="text" size="5" id="txtCounter" /><button type="button" class="counter increase">+</button>'));
// Initialise the value to 0
$("#txtCounter").val(0);
}
addElement++;
});
// Increment/decrement count
$(document).on("click", ".counter", function() {
var $input = $("#txtCounter");
if ($(this).hasClass('increase')) {
$input.val(parseInt($input.val()) + 1);
} else if ($input.val() >= 1) {
$input.val(parseInt($input.val()) - 1);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="page-wrap">
<h1>Cart Inc Dec</h1>
<a href="#" class="btn btn-info btn-lg mt-5 mr-5 mb-5">
<span class="glyphicon glyphicon-shopping-cart"><span id="itemCount"></span></span> Check Out
</a>
<br>
<a id="btnAddItem" class="btn btn-primary float-right mt-5 mb-5 mr-5">ADD</a>
<div class="addItem">
</div>
</div>
You can change the script and try something like below:
var addElement = 0;
var myCounter= function(action){
var val = document.getElementById("txtCounter").value;
val = parseInt(val);
if(action == 2){ //Increase
document.getElementById("txtCounter").value=val+1;
}else if(val > 1){
document.getElementById("txtCounter").value=val-1;
}
};
$(document).ready(function(){
$("#btnAddItem").on("click", function (event) {
if(addElement==0){
$(".addItem").append(('<button type="button" onclick="myCounter(1);" class="counter decrease">-</button><input type="text" size="5" id="txtCounter" value="0" /><button type="button" onclick="myCounter(2);" class="counter increase">+</button>'));
}
addElement++;
});
});

JavaScript - getElementsByClassName works for one function but not the other

I am trying to code a simple page where each click will change the pricing on the website using getElementsByClassName.
This is working :
<script>
function monthly() {
var price = document.getElementsByClassName("price");
price[0].innerHTML = "$10";
price[1].innerHTML = "$20";
price[2].innerHTML = "$30";
price[3].innerHTML = "$40";
}
</script>
<button onclick="monthly()">Monthly</button>
<button onclick="1year()">1 year</button>
<button onclick="2year()">2 year</button>
<button onclick="3year()">3 year</button>
<br>
<span class="price">$1</span><br>
<span class="price">$2</span><br>
<span class="price">$3</span><br>
<span class="price">$4</span><br>
Not working after adding 1year():
<script>
function monthly() {
var price = document.getElementsByClassName("price");
price[0].innerHTML = "$10";
price[1].innerHTML = "$20";
price[2].innerHTML = "$30";
price[3].innerHTML = "$40";
}
function 1year() {
var price2 = document.getElementsByClassName("price");
price2[0].innerHTML = "$8";
price2[1].innerHTML = "$16";
price2[2].innerHTML = "$24";
price2[3].innerHTML = "$32";
}
</script>
<button onclick="monthly()">Monthly</button>
<button onclick="1year()">1 year</button>
<button onclick="2year()">2 year</button>
<button onclick="3year()">3 year</button>
<br>
<span class="price">$1</span><br>
<span class="price">$2</span><br>
<span class="price">$3</span><br>
<span class="price">$4</span><br>
Does anyone know why?
TIA.
A function or variable in JavaScript cannot start with a number.
Identifiers must start with either a dollar sign ($), an underscore (_) or a unicode character.
In your case,
<button onclick="1year()">1 year</button>
<button onclick="2year()">2 year</button>
<button onclick="3year()">3 year</button>
All 3 functions are invalid.
Thanks to #Richard Hamilton, this is the full working code snipplet.
<script>
function monthly() {
var price = document.getElementsByClassName("price");
price[0].innerHTML = "$10";
price[1].innerHTML = "$20";
price[2].innerHTML = "$30";
price[3].innerHTML = "$40";
}
function annually() {
var price = document.getElementsByClassName("price");
price[0].innerHTML = "$8";
price[1].innerHTML = "$16";
price[2].innerHTML = "$24";
price[3].innerHTML = "$32";
}
</script>
<button onclick="monthly()">Monthly</button>
<button onclick="annually()">1 year</button>
<br>
<span class="price">$1</span><br>
<span class="price">$2</span><br>
<span class="price">$3</span><br>
<span class="price">$4</span><br>

Categories

Resources