transfer content from one element to another element with javascript - javascript

How to transfer list A to list B by clicking on BtnB?
With my code, I manage to transfer the content by clicking the BTNB, but when I click again on the BTNA, the numbers no longer appear in list A as expected but in list B
document.getElementById("buttonTryA").onclick = takeNumberA;
function takeNumberA() {
var x = document.getElementById("myNumber").value;
document.getElementById("listA").appendChild(document.createTextNode(`${x} `));
}
document.getElementById("buttonTryB").onclick = appendIt;
function appendIt() {
var source = document.getElementById("listA");
document.getElementById("listB").appendChild(source);
}
section {
display: flex;
flex-wrap: wrap;
}
.titleA {
margin-left: 50px;
margin-right: 180px;
}
#listNumber {
width: 200px;
height: 300px;
border: thin solid #ccc;
}
<body>
Number: <input type="number" id="myNumber" min="1" max="9">
<p>Click the BtnA to display the number of the number field (list A).</p>
<section>
<h1 class="titleA"> List A </h1>
<h1> List B </h1>
</section>
<section>
<button id="buttonTryA">BTNA</button>
<div id="listNumber">
<p id="listA"></p>
</div>
<button id="buttonTryB">BTNB</button>
<div id="listNumber">
<p id="listB"></p>
</div>
</section>
</body>

You're transfering the entire listA element to listB, not just its contents.
You should loop over the children of listA and transfer each of them.
I convert source.childNodes to an array for the iteration because moving the nodes removes them from the childNodes list, which would make the iteration skip nodes.
document.getElementById("buttonTryA").onclick = takeNumberA;
function takeNumberA() {
var x = document.getElementById("myNumber").value;
document.getElementById("listA").appendChild(document.createTextNode(`${x} `));
}
document.getElementById("buttonTryB").onclick = appendIt;
function appendIt() {
var source = document.getElementById("listA");
Array.from(source.childNodes).forEach(child =>
document.getElementById("listB").appendChild(child));
}
section {
display: flex;
flex-wrap: wrap;
}
.titleA {
margin-left: 50px;
margin-right: 180px;
}
#listNumber {
width: 200px;
height: 300px;
border: thin solid #ccc;
}
<body>
Number: <input type="number" id="myNumber" min="1" max="9">
<p>Click the BtnA to display the number of the number field (list A).</p>
<section>
<h1 class="titleA"> List A </h1>
<h1> List B </h1>
</section>
<section>
<button id="buttonTryA">BTNA</button>
<div id="listNumber">
<p id="listA"></p>
</div>
<button id="buttonTryB">BTNB</button>
<div id="listNumber">
<p id="listB"></p>
</div>
</section>
</body>

Related

How can i get these Javascript functions to increment correctly without combining with my original variable?

I'm currently doing a Javascript challenge on Scrimba that requires you to recreate a Basketball scoreboard. I've gotten the design down but i'm having trouble with increment buttons to add either 1,2, or 3 points to either teams score. Each team's scoreboard has 3 buttons underneath that can add 1,2, or 3 points. Originally i was just going to write 6 functions, 3 for each team that would function based on which increment button you select for which team. I figured i could probably just write the three separate increment functions and find a way to pass in an argument to direct which team was getting the points. This worked except that the functions all target a 'points' variable so they end up incrementing off of each other when you add points to the opposite team.
Here is the HTML
<div class="container">
<div class="column">
<h3 class="title">HOME</h3>
<h2 class="score" id="home-score">0</h2>
<div>
<button class="increment-btn" onclick="add1Point('home-score')">+1</button>
<button class="increment-btn" onclick="add2Points('home-score')">+2</button>
<button class="increment-btn" onclick="add3Points('home-score')">+3</button>
</div>
</div>
<div class="column">
<h3 class="title">GUEST</h3>
<h2 class="score" id="guest-score">0</h2>
<div>
<button class="increment-btn" onclick="add1Point('guest-score')">+1</button>
<button class="increment-btn" onclick="add2Points('guest-score')">+2</button>
<button class="increment-btn" onclick="add3Points('guest-score')">+3</button>
</div>
And here is the JS
let points = 0
function add1Point(idValue){
let teamId = document.getElementById(idValue)
points += 1
teamId.textContent = points
}
function add2Points(idValue){
let teamId = document.getElementById(idValue)
points += 2
teamId.textContent = points
}
function add3Points(idValue){
let teamId = document.getElementById(idValue)
points += 3
teamId.textContent = points
}
I know i need to find a way to have two separate point variables for each team but I'm not sure how i can point the individual functions to a specific variable base on which teams button is selected. Not without creating a whole new function specifically for that variable. If possible i would like a solution with the most basic vanilla JS possible, I know there are more complex ways to solve this but im only so far with my learning. Thanks in advance!
use closures
function score(points = 0) {
return function(value) {
points += value;
return points;
}
}
const $homeScore = document.getElementById("home-score");
const $guestScore = document.getElementById("guest-score");
const homeScore = score();
const guestScore = score();
const $homeButtons = document.querySelectorAll("#home-buttons button");
const $guestButtons = document.querySelectorAll("#guest-buttons button");
for(let i = 0; i < $homeButtons.length; i++) {
$homeButtons[i].addEventListener("click", () => {
$homeScore.innerText = homeScore(i + 1);
});
}
for(let i = 0; i < $guestButtons.length; i++) {
$guestButtons[i].addEventListener("click", () => {
$guestScore.innerText = guestScore(i + 1);
});
}
.container {
display: flex;
justify-content: space-between;
background-color: black;
color: white;
font-family: Courier, Courier New, monospace;
padding: 2px 5px;
}
.container .column .score {
border: 1px solid white;
border-radius: 2px;
padding: 2px 5px;
text-align: center;
}
<div class="container">
<div class="column">
<h3 class="title">HOME</h3>
<h2 class="score" id="home-score">0</h2>
<div id="home-buttons">
<button class="increment-btn">+1</button>
<button class="increment-btn">+2</button>
<button class="increment-btn">+3</button>
</div>
</div>
<div class="column">
<h3 class="title">GUEST</h3>
<h2 class="score" id="guest-score">0</h2>
<div id="guest-buttons">
<button class="increment-btn">+1</button>
<button class="increment-btn">+2</button>
<button class="increment-btn">+3</button>
</div>
</div>
</div>
As far as I understand, you'd probably need 2 individual variables to hold the value for each team, here's an example for add 1 point
let guest = 0;
let home = 0;
function add1Point(idValue){
let teamId = document.getElementById(idValue)
if (idValue === 'guest-score') { //Assume your element has name to tell them apart
guest += 1;
teamId.textContent = guest;
} else {
home += 1;
teamId.textContent = home;
}
}
In the other hand, you should make your method reusable and flexible a little like this
function addPoints(idValue, point) {
let teamId = document.getElementById(idValue)
if (idValue === 'guest-score') { //Assume your element has name to tell them apart
guest += point;
teamId.textContent = guest;
} else {
home += point;
teamId.textContent = home;
}
}
then your code will look cleaner
<button class="increment-btn" onclick="addPoints('guest-score', 1)">+1</button>
<button class="increment-btn" onclick="addPoints('guest-score', 2)">+2</button>
<button class="increment-btn" onclick="addPoints('guest-score', 3)">+3</button>
You can simplify it to one function only:
var homeScore = 0;
var guestScore = 0;
var homeScoreEl = document.getElementById('home-score');
var guestScoreEl = document.getElementById('guest-score');
function addPoints(isHome, points = 1) {
window[isHome ? 'homeScore' : 'guestScore'] += points
window[isHome ? 'homeScoreEl' : 'guestScoreEl'].textContent = window[isHome ? 'homeScore' : 'guestScore']
}
.container {
display: flex;
justify-content: space-between;
background-color: black;
color: white;
font-family: Courier, Courier New, monospace;
padding: 2px 5px;
}
.container .column .score {
border: 1px solid white;
border-radius: 2px;
padding: 2px 5px;
text-align: center;
}
<div class="container">
<div class="column">
<h3 class="title">HOME</h3>
<h2 class="score" id="home-score">0</h2>
<div>
<button class="increment-btn" onclick="addPoints(true)">+1</button>
<button class="increment-btn" onclick="addPoints(true, 2)">+2</button>
<button class="increment-btn" onclick="addPoints(true, 3)">+3</button>
</div>
</div>
<div class="column">
<h3 class="title">GUEST</h3>
<h2 class="score" id="guest-score">0</h2>
<div>
<button class="increment-btn" onclick="addPoints(false)">+1</button>
<button class="increment-btn" onclick="addPoints(false, 2)">+2</button>
<button class="increment-btn" onclick="addPoints(false, 3)">+3</button>
</div>

replace a div hidden intially by a click on a link from 3 other 3 linkes(3 other divs)

Hi I want to replace a div that is already displayed with another Hidden div choosed when i click on one of them(3 other divs(hidden) initially). the 4 links related to the 4 divs and in same way i can do that in each link clicked. below is the code:
<script type="text/javascript">
#4 Id of divs
var models = document.getElementById('models')
var geometry = document.getElementById('geometry')
var assembly = document.getElementById('assembly')
var loads = document.getElementById('loads')
#4 ID OF links (related to each div)
var models1 = document.getElementById('models1')
var geometryy = document.getElementById('geometryy')
var assemblyy = document.getElementById('assemblyy')
var loads1 = document.getElementById('loads1')
geometryy.addEventListener("click", function () {
models.style.display = "none"
loads.style.display = "none"
assembly.style.display = "none"
geometry.style.display = "block"
})
assemblyy.addEventListener("click", function () {
geometry.style.display = "none"
models.style.display = "none"
loads.style.display = "none"
assembly.style.display = "block"
})
loads1.addEventListener("click", function () {
geometry.style.display = "none"
models.style.display = "none"
assembly.style.display = "none"
loads.style.display = "block"
})
models1.addEventListener("click", function () {
models.style.display = "block"
geometry.style.display = "none"
assembly.style.display = "none"
loads.style.display = "none"
})
</script>
CSS:
<style>
#loads {
display: none;
}
#geometry {
display: none;
}
#assembly {
display: none;
}
#models {
display: block;
}
</style>
some Html code about the 4 divs:
<form action="{% url 'results' %}" method="post" id="gallery" novalidate onsubmit="return mySubmitFunction(event)">
<div style="padding-top: 10px; margin-left:138px;" class="parallax-window tm-section tm-section-gallery tm-flex background " id="models" >
<div style=" background-color: white; font-size:89%; width: 62rem; height: 32rem; margin-left:2.5rem; ">
<div class="card-warning" style="background-color: #C0C0C0;">
<nav class="navbar">
<a class="floated" style="font-weight: bolder; border-style: solid;" id="models1">Models</a>
Geometry
Assembly
Loads
</nav>
</div>
.......... some fields related to the div id="models"
</div>
</div>
----------------About the second div
<div style="padding-top: 10px;" class="parallax-window tm-section tm-section-gallery tm-flex" id="geometry" >
<div style=" background-color: white; font-size:89%; width: 62rem; height: 32rem; margin-left:2.5rem; ">
<div class="card-warning" style="background-color: #C0C0C0;">
<nav class="navbar">
Models
<a class="floated" style=" font-weight: bolder; border-style: solid;">Geometry</a>
Assembly
Loads
</nav>
</div>
<div style="display: flex;">
<div>
<img style="height: 372px; width:270px; margin-left: 25px;">
</div>
<div style="line-height: 0.001; margin-left: 10px; margin-top: 12px;">
------ some code for some fields
</div>
</div>
...... </div>
---- </div>
----------------About the third div
<div style="padding-top: 10px;" class="parallax-window tm-section tm-section-gallery tm-flex" id="assembly" >
<div style="background-color: white; font-size:89%; width: 62rem; height: 32rem; margin-left:2.5rem; ">
<div class="card-warning" style="background-color: #C0C0C0;">
<nav class="navbar">
Models
Geometry
<a class="floated" style=" font-weight: bolder; border-style: solid;">Assembly</a>
<a href="#loads" class="floated" style=" font-weight: bolder;" id="loads3" >Loads</a>
</nav>
</div>
<div style="display: flex;">
<div>
<img style="height: 372px; width:270px; margin-left: 25px;">
</div>
<div style="line-height: 0.001; margin-left: 10px; margin-top: 12px;">
------ some code for some fields
</div>
</div>
...... </div>
---- </div>
----------------About the fourth div
<div style="padding-top: 10px; " class="parallax-window tm-section tm-section-gallery tm-flex" id="loads" >
<div style="background-color: white; font-size:89%; width: 62rem; height: 32rem; margin-left:2.5rem;">
<div class="card-warning" style="background-color: #C0C0C0;">
<nav class="navbar">
<a href="#models" class="floated" style="font-weight: bolder;" >Models</a>
Geometry
Assembly
<a style=" font-weight: bolder; border-style: solid;">Loads</a>
</nav>
</div>
<div style="display: flex;">
<div>
<img style="height: 372px; width:270px; margin-left: 25px;">
</div>
<div style="line-height: 0.001; margin-left: 10px; margin-top: 12px;">
------ some code for some fields
</div>
</div>
...... </div>
---- </div>
</form>
what i want :at first the "models" div is shown and the other 3 divs("geometry",assembly","loads") are hidden , so i want when i click on "geometry" div , the first div "models" become hidden and the other divs ("assembly" and "loads" still hidden) and so on if click on assembly... i i want to apply that on every div(because evry div has the 4 links)
But it doesn't give me any result!
<html>
<head>
<style>
#div2, #div3, #div4{
display: none;
}
</style>
</head>
<body>
<div style="background-color: #C0C0C0 ;padding-top: 10px;width: 62rem; height: 32rem; ">
<div>
<a href="#models" class="geo wy" style="border-style: solid;" >Models</a>
Geometry
Assembly
Loads
</div>
<div id="div1" class="wy hid">
Models and other stuffs here
</div>
<div id="div2" class="pk hid">
Geometry and other stuffs here
</div>
<div id="div3" class="fk hid">
Assembly and other stuffs here
</div>
<div id="div4" class="gk hid">
Loads and other stuffs here
</div>
</div>
<script>
window.onload = btn() ;
function btn() {
var query = document.querySelectorAll(".geo") ; //No of hrefs
var pts = document.querySelectorAll(".hid"); //No of divs
for(var i=0;i<query.length;i++){
query[i].addEventListener("click", function() { //know which href is being clicked currently
var cla = this.getAttribute('class').split(' ')[1] ; //get second class of current href which would be wy, pk, fk, gk respectively.
var point = document.querySelectorAll("."+cla)[1]; //selecting the div as, [0] would select the href
for(var j=0;j<pts.length;j++){
pts[j].style.display = "none"; //hid all the div
query[j].style.border= "none"; //remove all the href border
}
this.style.border= "solid"; //Add currently clicked href border
point.style.display = "block"; //display currently clicked div
})
}
}
</script>
</body>
</html>
Sorry the id and classes name are given random i am not good at naming. Please don't hesitate to ask if you are confused

Modal Window on card click JS CSS PHP

So I have 6 cards on my html. Each one on click need to pop up a modal window (this modal window is the card with more informations, so each modal window is corresponding to one card).
I dont know how to do that. After a day searching on the web I'm here to ask your help.
I have tried to make the html animal_card, and my modal appart. Then all the content will change with php.
And the Javascript need to change the modal window css property to absolute on click.
Someone know how to do that with Javascript ?
HTML :
<div class="animal_card">
<div class="card_title">
<h3>title</h3>
</div>
<div class="card_image">
<img src="image.img" alt="">
</div>
<div class="card_text">
<div class="card_info">
<div class="card_info_age">
<h4>Age</h4>
<p>14</p>
</div>
<div class="card_info_gender">
<h4>Gender :</h4>
<p>Female</p>
</div>
</div>
<h4>Who am I</h4>
<p>Description Text</p>
</div>
</div>
<div class="bg-modal">
<div class="modal-content">
<div class="modal-animal">
<h1>Animal Name</h1>
<button class="close" onclick="closeModal()">&times</button>
<div><img src="img/greciaprofile.jpg" alt=""></div>
<div class="animal-informations">
<div class="left">
<label for="">Age</label>
<p>14</p>
<label for="">Sexe</label>
<p>Female</p>
</div>
<div class="right">
<label for="">Description</label>
<p>
Text
</p>
</div>
</div>
<div>
<button class="main">Adopt</button>
<button class="secondary">Support</button>
</div>
</div>
</div>
</div>
CSS :
.bg-modal {
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.7);
position: absolute;
top: 0;
left: 0;
display: flex;
justify-content: center;
}
.modal-content {
position: absolute;
margin-top: 5rem;
width: 75vw;
background-color: $white;
border-radius: 15px;
}
Javascript :
const cards = document.querySelectorAll('.animal_card');
const modal = document.getElementsByClassName('bg-modal');
const onCardClick = async (e) => {
const card = e.currentTarget;
modal.style.position = 'absolute';
}
cards.forEach(card => card.addEventListener('click', onCardClick));
function closeModal() {
modal[0].style.position = 'none';
}
const cards = document.querySelectorAll('.animal_card');
const modal = document.getElementsByClassName('bg-modal');
const getKeyMap = (modal) => {
if (modal) {
let i;
let keyMap = {};
for (i = 0; i < modal.length; i++) {
const item = modal[i];
const key = item.getAttribute('key');
keyMap[key] = item;
}
return keyMap;
}
return null;
};
const modalMap = getKeyMap(modal);
const onCardClick = async (e) => {
const card = e.currentTarget && e.currentTarget.getAttribute('key') || null;
const selectedModal = modalMap[card] || null;
if (selectedModal) {
selectedModal.style.position = 'absolute';
}
}
cards.forEach(card => card.addEventListener('click', onCardClick));
.bg-modal {
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.7);
/* position: absolute; */
top: 0;
left: 0;
display: flex;
justify-content: center;
}
.modal-content {
position: absolute;
margin-top: 5rem;
width: 75vw;
background-color: $white;
border-radius: 15px;
}
<div key="5" class="animal_card">
<div class="card_title">
<h3>title</h3>
</div>
<div class="card_image">
<img src="image.img" alt="">
</div>
<div class="card_text">
<div class="card_info">
<div class="card_info_age">
<h4>Age</h4>
<p>14</p>
</div>
<div class="card_info_gender">
<h4>Gender :</h4>
<p>Female</p>
</div>
</div>
<h4>Who am I</h4>
<p>Description Text</p>
</div>
</div>
<div class="bg-modal" key="5">
<div class="modal-content">
<div class="modal-animal">
<h1>Animal Name</h1>
<button class="close">&times</button>
<div><img src="img/greciaprofile.jpg" alt=""></div>
<div class="animal-informations">
<div class="left">
<label for="">Age</label>
<p>14</p>
<label for="">Sexe</label>
<p>Female</p>
</div>
<div class="right">
<label for="">Description</label>
<p>
Text
</p>
</div>
</div>
<div>
<button class="main">Adopt</button>
<button class="secondary">Support</button>
</div>
</div>
</div>
</div>
So the direct answer using your example is modal on the onCardClick is returning a collection, not a single element. So selecting the first one modal[0] will fix the position update. I attached an example.
If you are going to show different modals based on the card you click on, you generally need to have a method to track them. Really depends on how you want to do that, based on ids, or index position or so on. Anyways, let me know if this helps.

Order "form", final calculation not computing

This is supposed to be a simple pure html, css and javascript order form with four fields for four different product. Users can adjust quantity and calculate totals for each product and for the final total. Everything is working except the final calculation and I have no idea why because it uses the same methods I used to calculate the individual totals.
<!DOCTYPE html>
<html>
<head>
<title>Order Form</title>
<style>
#productOnePrice, #productOneName, #productOneQuantity, #productOneTotal,
#productTwoPrice, #productTwoName, #productTwoQuantity, #productTwoTotal,
#productThreePrice, #productThreeName, #productThreeQuantity,
#productThreeTotal, #productFourPrice, #productFourName,
#productFourQuantity, #productFourTotal, #orderTotalButton, #orderTotal{
height:20px;
width:238px;
float:left;
margin: 5px 5px 5px 5px;
padding: 1px 1px 1px 1px;
outline: 2px solid black;
text-align: center;
}
.container {
height:auto;
width:1000px;
float:left;
padding: 5px 5px 5px 5px;
outline: 2px solid black;
text-align: center;
}
.quantityOne{
text-align: right;
}
</style>
</head>
<body>
<div class="container">
<!-- Product One -->
<div>
<p id="productOneName"></p>
</div>
<div>
<p id="productOnePrice"></p>
</div>
<div>
<p id="productOneQuantity">
<input id="quantityOne" type="number">
<button onclick="productOneTotal()">Add</button>
</p>
</div>
<div>
<p id="productOneTotal"></p>
</div>
<!-- Product Two -->
<div>
<p id="productTwoName"></p>
</div>
<div>
<p id="productTwoPrice"></p>
</div>
<div>
<p id="productTwoQuantity">
<input id="quantityTwo" type="number">
<button onclick="productTwoTotal()">Add</button>
</p>
</div>
<div>
<p id="productTwoTotal"></p>
</div>
<!-- Product Three -->
<div>
<p id="productThreeName"></p>
</div>
<div>
<p id="productThreePrice"></p>
</div>
<div>
<p id="productThreeQuantity">
<input id="quantityThree" type="number">
<button onclick="productThreeTotal()">Add</button>
</p>
</div>
<div>
<p id="productThreeTotal"></p>
</div>
<!-- Product Four -->
<div>
<p id="productFourName"></p>
</div>
<div>
<p id="productFourPrice"></p>
</div>
<div>
<p id="productFourQuantity">
<input id="quantityFour" type="number">
<button onclick="productFourTotal()">Add</button>
</p>
</div>
<div>
<p id="productFourTotal"></p>
</div>
<!-- Order Total -->
<div>
<p id="orderTotalButton">
<button onclick="orderTotal()">Add</button>
</p>
</div>
<div>
<p id="orderTotal"></p>
</div>
<script>
/* Product One Total Function */
document.getElementById("productOneName").innerText = "mp3";
document.getElementById("productOnePrice").innerHTML = 1;
function productOneTotal(price, quantity){
price = 1;
quantity = document.getElementById("quantityOne").value;
document.getElementById("productOneTotal").innerHTML =
parseInt(price) * parseInt(quantity);
}
/* Product Two Total Function */
document.getElementById("productTwoName").innerText = "Cassette";
document.getElementById("productTwoPrice").innerHTML = 1;
function productTwoTotal(price, quantity){
price = 1;
quantity = document.getElementById("quantityTwo").value;
document.getElementById("productTwoTotal").innerHTML =
parseInt(price) * parseInt(quantity);
}
/* Product Three Total Function */
document.getElementById("productThreeName").innerText = "Vinyl LP";
document.getElementById("productThreePrice").innerHTML = 1;
function productThreeTotal(price, quantity){
price = 1;
quantity = document.getElementById("quantityThree").value;
document.getElementById("productThreeTotal").innerHTML =
parseInt(price) * parseInt(quantity);
}
/* Product Four Total Function */
document.getElementById("productFourName").innerText = "T-Shirt";
document.getElementById("productFourPrice").innerHTML = 1;
function productFourTotal(price, quantity){
price = 1;
quantity = document.getElementById("quantityFour").value;
document.getElementById("productFourTotal").innerHTML =
parseInt(price) * parseInt(quantity);
}
/* Order Total Function */
function orderTotal(productOneTotal, productTwoTotal,
productThreeTotal, productFourTotal){
productOneTotal =
document.getElementById("productOneTotal").value;
productTwoTotal =
document.getElementById("productTwoTotal").value;
productThreeTotal =
document.getElementById("productThreeTotal").value;
productFourTotal =
document.getElementById("productFourTotal").value;
document.getElementById("orderTotal").innerHTML =
parseInt(productOneTotal) + parseInt(productTwoTotal) +
parseInt(productThreeTotal) + parseInt(productFourTotal);
}
</script>
</div>
</body>
</html>
You need to target your total elements with .innerHTML instead of value.
productOneTotal = document.getElementById("productOneTotal").innerHTML;
That'll remove the NaN error you were getting. The elements don't have a value so attempts to retrieve .value were returning undefined.
NOTE: Textbox, and other elements .value is used. and div elements gain value we have use .innerHTML
<!DOCTYPE html>
<html>
<head>
<title>Order Form</title>
<style>
#productOnePrice, #productOneName, #productOneQuantity, #productOneTotal,
#productTwoPrice, #productTwoName, #productTwoQuantity, #productTwoTotal,
#productThreePrice, #productThreeName, #productThreeQuantity,
#productThreeTotal, #productFourPrice, #productFourName,
#productFourQuantity, #productFourTotal, #orderTotalButton, #orderTotal{
height:20px;
width:238px;
float:left;
margin: 5px 5px 5px 5px;
padding: 1px 1px 1px 1px;
outline: 2px solid black;
text-align: center;
}
.container {
height:auto;
width:1000px;
float:left;
padding: 5px 5px 5px 5px;
outline: 2px solid black;
text-align: center;
}
.quantityOne{
text-align: right;
}
</style>
</head>
<body>
<div class="container">
<!-- Product One -->
<div>
<p id="productOneName"></p>
</div>
<div>
<p id="productOnePrice"></p>
</div>
<div>
<p id="productOneQuantity">
<input id="quantityOne" type="number">
<button onclick="productOneTotal()">Add</button>
</p>
</div>
<div>
<p id="productOneTotal"></p>
</div>
<!-- Product Two -->
<div>
<p id="productTwoName"></p>
</div>
<div>
<p id="productTwoPrice"></p>
</div>
<div>
<p id="productTwoQuantity">
<input id="quantityTwo" type="number">
<button onclick="productTwoTotal()">Add</button>
</p>
</div>
<div>
<p id="productTwoTotal"></p>
</div>
<!-- Product Three -->
<div>
<p id="productThreeName"></p>
</div>
<div>
<p id="productThreePrice"></p>
</div>
<div>
<p id="productThreeQuantity">
<input id="quantityThree" type="number">
<button onclick="productThreeTotal()">Add</button>
</p>
</div>
<div>
<p id="productThreeTotal"></p>
</div>
<!-- Product Four -->
<div>
<p id="productFourName"></p>
</div>
<div>
<p id="productFourPrice"></p>
</div>
<div>
<p id="productFourQuantity">
<input id="quantityFour" type="number">
<button onclick="productFourTotal()">Add</button>
</p>
</div>
<div>
<p id="productFourTotal"></p>
</div>
<!-- Order Total -->
<div>
<p id="orderTotalButton">
<button onclick="orderTotal()">Add</button>
</p>
</div>
<div>
<p id="orderTotal"></p>
</div>
<script>
/* Product One Total Function */
document.getElementById("productOneName").innerText = "mp3";
document.getElementById("productOnePrice").innerHTML = 1;
function productOneTotal(){
price = 1;
quantity = document.getElementById("quantityOne").value;
if(quantity=="") {
quantity = 0;
}
document.getElementById("productOneTotal").innerHTML =
parseInt(price) * parseInt(quantity);
}
/* Product Two Total Function */
document.getElementById("productTwoName").innerText = "Cassette";
document.getElementById("productTwoPrice").innerHTML = 1;
function productTwoTotal(){
price = 1;
quantity = document.getElementById("quantityTwo").value;
if(quantity=="") {
quantity = 0;
}
document.getElementById("productTwoTotal").innerHTML =
parseInt(price) * parseInt(quantity);
}
/* Product Three Total Function */
document.getElementById("productThreeName").innerText = "Vinyl LP";
document.getElementById("productThreePrice").innerHTML = 1;
function productThreeTotal(){
price = 1;
quantity = document.getElementById("quantityThree").value;
if(quantity=="") {
quantity = 0;
}
document.getElementById("productThreeTotal").innerHTML =
parseInt(price) * parseInt(quantity);
}
/* Product Four Total Function */
document.getElementById("productFourName").innerText = "T-Shirt";
document.getElementById("productFourPrice").innerHTML = 1;
function productFourTotal(){
price = 1;
quantity = document.getElementById("quantityFour").value;
if(quantity=="") {
quantity = 0;
}
document.getElementById("productFourTotal").innerHTML =
parseInt(price) * parseInt(quantity);
}
/* Order Total Function */
function orderTotal(productOneTotal, productTwoTotal,
productThreeTotal, productFourTotal){
productOneTotal =
document.getElementById("productOneTotal").innerHTML;
productTwoTotal =
document.getElementById("productTwoTotal").innerHTML;
productThreeTotal =
document.getElementById("productThreeTotal").innerHTML;
productFourTotal =
document.getElementById("productFourTotal").innerHTML;
if(productOneTotal=="") {
productOneTotal=0;
}
if(productTwoTotal=="") {
productTwoTotal=0;
}
if(productThreeTotal=="") {
productThreeTotal=0;
}
if(productFourTotal=="") {
productFourTotal=0;
}
document.getElementById("orderTotal").innerHTML =
parseInt(productOneTotal) + parseInt(productTwoTotal) +
parseInt(productThreeTotal) + parseInt(productFourTotal);
}
</script>
</div>
</body>
</html>

Creating a star rating from an image based on a float number?

recently I have wanted to turn a number into a star rating and I stumbled upon this post here: https://stackoverflow.com/a/1987545/1871869 which is exactly what I wanted to do. I have followed this explanation but I can't seem to get it to work on my local environment, and I was wondering if someone could help me out. Here is my attempt:
$.fn.stars = function() {
return $(this).each(function() {
// Get the value
var val = parseFloat($(this).html());
// Make sure that the value is in 0 - 5 range, multiply to get width
var size = Math.max(0, (Math.min(5, val))) * 16;
// Create stars holder
var $span = $('<span />').width(size);
// Replace the numerical value with stars
$(this).html($span);
});
}
$(function() {
console.log("Calling stars()");
$('.results-contents span.stars').stars();
});
.results {
font-size: 0;
padding-bottom: 16px;
}
.results-content {
font-size: 13px;
display: inline-block;
margin-left: 20px;
vertical-align: top;
}
.results .results-content span.stars span.stars span {
background: url('/resources/graphics/stars-icons.png') 0 -36px repeat-x;
width: 175px;
height: 80px;
}
.results .results-content span.stars {
max-width: 80px;
background-position: 0 0;
}
<script type="text/template" id="results-template">
<div class="results">
<div class="results-content">
<span class="stars">4.0</span>
</div>
</div>
</script>
Image of stars:
What I wanted to do was to simply have the empty stars show, and then based on the rating, show the orange stars on top of the empty stars so that I can show full and half star ratings. However, all I get is a number to show up. My console.log above seems to be called but it seems like the actual rendering of the image and calculation of the star rating is not working. Any help would be appreciated. Thanks!
You had multiple issues from CSS styles being wrong to your selector being wrong. Below is not perfect, but it is rendering.
$.fn.stars = function() {
return this.each(function() {
// Get the value
var val = parseFloat($(this).html());
// Make sure that the value is in 0 - 5 range, multiply to get width
var size = Math.max(0, (Math.min(5, val))) * 36.5;
// Create stars holder
var $span = $('<span> </span>').width(size);
// Replace the numerical value with stars
$(this).empty().append($span);
});
}
$(function() {
console.log("Calling stars()");
$('.results-content span.stars').stars();
});
.results {
font-size: 0;
padding-bottom: 16px;
}
.results-content {
font-size: 13px;
display: inline-block;
margin-left: 20px;
vertical-align: top;
background: url('https://i.stack.imgur.com/rwkqF.png') 0 0 repeat-x;
width: 185px;
height: 35px;
}
.results .results-content span.stars span {
background: url('https://i.stack.imgur.com/rwkqF.png') 0 -36px repeat-x;
display: inline-block;
height: 35px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="results">
<div class="results-content">
<span class="stars">0.0</span>
</div>
</div>
<div class="results">
<div class="results-content">
<span class="stars">0.5</span>
</div>
</div>
<div class="results">
<div class="results-content">
<span class="stars">1.0</span>
</div>
</div>
<div class="results">
<div class="results-content">
<span class="stars">1.5</span>
</div>
</div>
<div class="results">
<div class="results-content">
<span class="stars">2.0</span>
</div>
</div>
<div class="results">
<div class="results-content">
<span class="stars">2.0</span>
</div>
</div>
<div class="results">
<div class="results-content">
<span class="stars">2.5</span>
</div>
</div>
<div class="results">
<div class="results-content">
<span class="stars">3.0</span>
</div>
</div>
<div class="results">
<div class="results-content">
<span class="stars">3.5</span>
</div>
</div>
<div class="results">
<div class="results-content">
<span class="stars">4.0</span>
</div>
</div>
<div class="results">
<div class="results-content">
<span class="stars">4.5</span>
</div>
</div>
<div class="results">
<div class="results-content">
<span class="stars">5.0</span>
</div>
</div>

Categories

Resources