JavaScript - getElementsByClassName works for one function but not the other - javascript

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>

Related

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

How to access the changed value of an onclick event?

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>

Simple calculator in html/javascript

I'm trying to make a calculator with html and JavaScript. After clicking on the button i'm trying to insert the number into my div. When i do so the default '0' disappears and it does not insert anything at all.
function copy(event) {
var newValue = event.target.value;
document.querySelector("#display").innerHTML = newValue;
}
var textfield = document.querySelector("#btn_7");
textfield.addEventListener("click", copy);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="frame">
<div id="display">0</div>
<button id="btn_7">7</button>
<button id="btn_8">8</button>
<button id="btn_9">9</button>
<button id="btn_div">/</button>
<button id="btn_4">4</button>
<button id="btn_5">5</button>
<button id="btn_6">6</button>
<button id="btn_prod">*</button>
<button id="btn_1">1</button>
<button id="btn_2">2</button>
<button id="btn_3">3</button>
<button id="btn_min">-</button>
<button id="btn_clear">C</button>
<button id="btn_0">0</button>
<button id="btn_eq">=</button>
<button id="btn_plus">+</button>
</div>
If I add a string to newValue variable it shows in my div. So it means like when I press on the button it doesnt give anything to the div. Is there a way to solve this?
And about var textfield = document.querySelector("#btn_7");
For now I have to make this for each button and thats will take a lot of rows is there a better way to do so?
Buttons don't have a default attribute value, so in this case use the attribute textContent.
I recommend you to use a hidden input to store the values or you can also use data-attributes.
For now i have to make this for each button and that will take alot of rows is there a better way to do so?
You can use the function document.querySelectorAll(selector) and loop over it to bind the specific event.
function copy(event) {
var newValue = event.target.textContent;
document.querySelector("#display").innerHTML = newValue;
}
Array.prototype.forEach.call(document.querySelectorAll('button'), function(b) {
b.addEventListener("click", copy);
});
<div id="frame">
<div id="display">0</div>
<button id="btn_7">7</button>
<button id="btn_8">8</button>
<button id="btn_9">9</button>
<button id="btn_div">/</button>
<button id="btn_4">4</button>
<button id="btn_5">5</button>
<button id="btn_6">6</button>
<button id="btn_prod">*</button>
<button id="btn_1">1</button>
<button id="btn_2">2</button>
<button id="btn_3">3</button>
<button id="btn_min">-</button>
<button id="btn_clear">C</button>
<button id="btn_0">0</button>
<button id="btn_eq">=</button>
<button id="btn_plus">+</button>
</div>
try like this
$(function(){
$('button[id^="btn_"]').click(function(){
var display;
if($('.tmp').length > 0){
display = $('.tmp').text();
}else{
$( "<p class='tmp' style='display:none;'></p>" ).appendTo( "#frame" );
display = '';
}
switch($(this).text()){
case 'C' :
display = '0';
break;
case '=' :
display = eval(display);
break;
default :
display = display.concat($(this).text());
}
$('#display').text(display);
$('.tmp').text((display != '0') ? display : '');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="frame">
<div id="display">0</div>
<button id="btn_7">7</button>
<button id="btn_8">8</button>
<button id="btn_9">9</button>
<button id="btn_div">/</button><br/>
<button id="btn_4">4</button>
<button id="btn_5">5</button>
<button id="btn_6">6</button>
<button id="btn_prod">*</button><br/>
<button id="btn_1">1</button>
<button id="btn_2">2</button>
<button id="btn_3">3</button>
<button id="btn_min">-</button><br/>
<button id="btn_clear">C</button>
<button id="btn_0">0</button>
<button id="btn_eq">=</button>
<button id="btn_plus">+</button>
</div>
Here is to select value and replace html of display div. You need to do some extra stuff to achieve what is your desired output.
var display = $('#display');
$('.btn').click(function(e) {
var btn = e.target;
display.html(btn.id);
});
<script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script>
<div id="frame">
<div id="display">0</div>
<button class="btn" id="btn_7">7</button>
<button class="btn" id="btn_8">8</button>
<button class="btn" id="btn_9">9</button>
<button class="btn" id="btn_div">/</button>
<button class="btn" id="btn_4">4</button>
<button class="btn" id="btn_5">5</button>
<button class="btn" id="btn_6">6</button>
<button class="btn" id="btn_prod">*</button>
<button class="btn" id="btn_1">1</button>
<button class="btn" id="btn_2">2</button>
<button class="btn" id="btn_3">3</button>
<button class="btn" id="btn_min">-</button>
<button class="btn" id="btn_clear">C</button>
<button class="btn" id="btn_0">0</button>
<button class="btn" id="btn_eq">=</button>
<button class="btn" id="btn_plus">+</button>
</div>

Script tag in ng repeat

I'm trying to set a an elements that are intially hidden but the script tag inside my ng-repeat is only executing once.
<h2 class="primary-header"> Get Settings </h2>
<div ng-repeat='feature in features'>
<p></p>
<button type="button" class="btn btn-default"
ng-click='genericGet(feature.func)'>
{{feature.tag}}
</button>
<div ng-hide={{feature.hide}}>
<pre>
{{feature.status | json}}
</pre>
</div>
</div>
$scope.features =[];
$scope.features[0] = {};
$scope.features[0].tag = 'pop';
$scope.features[0].hide = true;
$scope.features[0].status = '';
$scope.features[0].func = 0;
$scope.features[0].url = 'pop';
$scope.genericGet = function(number){
$scope.features[number].hide = false;
}

Categories

Resources