Get total price added up with jquery - javascript

Newbie on JS and got really stuck.
I have a plus and a minus button that adds up products. But I need that the result of this total price to adds up accordingly. And some of the products can only be bought with multiples of 2, 5 or 10.
I have here my html with 2 of my products. One that can only be sold with multiples of 5 and the other, multiple of 10.
<!-- Product #6 -->
<div class="item">
<div class="buttons">
<span class="delete-btn"></span>
<span class="like-btn"></span>
</div>
<div class="image">
<img src="intem-6.jpg" alt="" />
</div>
<div class="description">
<span>DLT-19 Heavy Blaster Rifle</span>
<span>Brown</span>
</div>
<div class="quantity">
<button class="plus-btn" type="button" name="button">
<img src="plus-btn.png" alt="" />
</button>
<input type="text" name="name" value="1">
<button class="minus-btn" type="button" name="button">
<img src="minus-btn.png" alt="" />
</button>
</div>
<div id="multiple5" class="total-price">$5800</div>
</div>
<!-- Product #7 -->
<div class="item">
<div class="buttons">
<span class="delete-btn"></span>
<span class="like-btn"></span>
</div>
<div class="image">
<img src="item-7.jpg" alt="" >
</div>
<div class="description">
<span>DL-44 Heavy Blaster Pistol</span>
<span>Brown</span>
</div>
<div class="quantity">
<button class="plus-btn" type="button" name="button">
<img src="plus-btn.png" alt="" />
</button>
<input type="text" name="name" value="1">
<button class="minus-btn" type="button" name="button">
<img src="minus-btn.png" alt="" />
</button>
</div>
<div id="multiple10" class="total-price">$1500</div>
</div>
</div>
And here is my jQuery that adds up 1 on.click of my buttons.
$('.minus-btn').on('click', function(e) {
e.preventDefault();
var $this = $(this);
var $input = $this.closest('div').find('input');
var value = parseInt($input.val());
if (value >= 1) {
value = value - 1;
} else {
value = 0;
}
$input.val(value);
});
$('.plus-btn').on('click', function(e) {
e.preventDefault();
var $this = $(this);
var $input = $this.closest('div').find('input');
var value = parseInt($input.val());
if (value < 100) {
value = value + 1;
} else {
value =100;
}
$input.val(value);
});
I tried doing separately along with my searches but couldn't implement this on my other code. Just want the result to add up and decrease the price along with the on.click event of my buttons.
<html>
<head>
<title>Hello</title>
<style>
*{
font-size: 25px;
}
</style>
</head>
<body>
<button id="plus"> + </button>
<input id="quantity" type="number" value='1'>
<button id="minus"> - </button>
<div id="total">5</div>
<script>
let plus = document.getElementById('plus');
let quantityEle = document.getElementById('quantity');
let minus = document.getElementById('minus');
let total = document.getElementById('total');
let quantity = quantityEle.value;
let price = 5;
plus.addEventListener('click', function(){
quantity++;
quantityEle.value = quantity;
total.innerHTML = price * quantity;
});
minus.addEventListener('click', function(){
if(quantity > 1)
quantity--;
quantityEle.value = quantity;
total.innerHTML = price * quantity;
});
quantityEle.addEventListener('change', function(){
quantity = quantityEle.value;
total.innerHTML = price * quantity;
});
var total = $this.closest('div').find('div');
</script>
</body>
</html>

Here you go!
$('.minus-btn').on('click', function(e) {
e.preventDefault();
var $parent = $(this).closest('.item');
var $input = $parent.find('input');
var $total = $parent.find('.total-price span');
var value = parseInt($input.val());
if (value >= 1) {
value = value - 1;
} else {
value = 0;
}
$input.val(value);
$total.html(value);
calcTotal();
});
$('.plus-btn').on('click', function(e) {
e.preventDefault();
var $parent = $(this).closest('.item');
var $input = $parent.find('input');
var $total = $parent.find('.total-price span');
var value = parseInt($input.val());
if (value < 100) {
value = value + 1;
} else {
value = 100;
}
$input.val(value);
$total.html(value);
calcTotal();
});
function calcTotal() {
let total = 0;
$(".total-price span").each(function() {
total += parseInt($(this).html());
});
$('#total').html('$' + total);
}
#total {
color: red;
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<!-- Product #6 -->
<div class="item">
<div class="buttons">
<span class="delete-btn"></span>
<span class="like-btn"></span>
</div>
<div class="image">
<img src="intem-6.jpg" alt="" />
</div>
<div class="description">
<span>DLT-19 Heavy Blaster Rifle</span>
<span>Brown</span>
</div>
<div class="quantity">
<button class="plus-btn" type="button" name="button">
<img src="plus-btn.png" alt="" /> +
</button>
<input type="text" name="name" value="1">
<button class="minus-btn" type="button" name="button">
<img src="minus-btn.png" alt="" /> -
</button>
</div>
<div id="multiple5" class="total-price">$<span>1</span></div>
</div>
<!-- Product #7 -->
<div class="item">
<div class="buttons">
<span class="delete-btn"></span>
<span class="like-btn"></span>
</div>
<div class="image">
<img src="item-7.jpg" alt="">
</div>
<div class="description">
<span>DL-44 Heavy Blaster Pistol</span>
<span>Brown</span>
</div>
<div class="quantity">
<button class="plus-btn" type="button" name="button">
<img src="plus-btn.png" alt="" /> +
</button>
<input type="text" name="name" value="1">
<button class="minus-btn" type="button" name="button">
<img src="minus-btn.png" alt="" /> -
</button>
</div>
<div id="multiple10" class="total-price">$<span>1</span></div>
</div>
<div>
Total: <span id="total">$2</span>
</div>

I think your question is really badly asked.
From what I understand, you seek to write an equivalence of jQuery in JS 'vanila' to increment decrement of (2, 5, 10) quantities and realize the corresponding totals.
so here is "my solution":
document
.querySelectorAll('button.minus')
.forEach(bt=>
{
bt.onclick=e=>
{
let P_parent = e.target.parentNode
, Inc = parseInt(P_parent.dataset.increment)
, U_price = parseFloat(P_parent.dataset.price).toFixed(2)
, val = parseInt(P_parent.querySelector('.quantity').value)
if (val > 0)
{
val -= Inc
P_parent.querySelector('.quantity').value = val
P_parent.querySelector('.total').textContent = '$ '+ (val * U_price).toFixed(2)
}
}
})
document
.querySelectorAll('button.plus')
.forEach(bt=>
{
bt.onclick=e=>
{
let P_parent = e.target.parentNode
, Inc = parseInt(P_parent.dataset.increment)
, U_price = parseFloat(P_parent.dataset.price).toFixed(2)
, Max = parseInt(P_parent.dataset.max)
, val = parseInt(P_parent.querySelector('.quantity').value)
if (val < Max)
{
val += Inc
P_parent.querySelector('.quantity').value = val
P_parent.querySelector('.total').textContent = '$ '+ (val * U_price).toFixed(2)
}
}
})
body { font: 14px sans-serif; padding: 1em; }
h3 { margin: 1.5em 0 0 0; }
input.quantity { width:4em; text-align: right }
.total { display: inline-block; width: 6em; text-align: right; font-weight: bold; border-bottom: 1px solid grey; margin-left: .5em }
p > button { font-weight: bold; }
<h3>by 2</h3>
<p data-increment="2" data-max=50 data-price="11">
<input class="quantity" type="text" value='0' readonly>
<button class="minus">-</button>
<button class="plus">+</button>
unit price : $11
<span class="total">$ 0</span>
</p>
<h3>by 5</h3>
<p data-increment="5" data-max=80 data-price="5.23">
<input class="quantity" type="text" value='0' readonly>
<button class="minus">-</button>
<button class="plus">+</button>
unit price : $5.23
<span class="total">$ 0</span>
</p>
<h3>by 10</h3>
<p data-increment="10" data-max=100 data-price="3.12">
<input class="quantity" type="text" value='0' readonly>
<button class="minus">-</button>
<button class="plus">+</button>
unit price : $3.12
<span class="total">$ 0</span>
</p>

Related

how to fix: Cannot read property 'value' of undefined

I am trying to get the value of the quantityElement so i can make the price change decrease/increase when the quantity goes down/up but i order for this to work i need to get the value of the quantityElement which keeps coming back as undefined in the console.
var removeCartitemButtons = document.getElementsByClassName('remove-btn')
console.log(removeCartitemButtons)
for (var i = 0; i < removeCartitemButtons.length; i++) {
var button = removeCartitemButtons[i]
button.addEventListener('click', function(event) {
console.log('clicked')
var buttonClicked = event.target
buttonClicked.parentElement.parentElement.remove()
updateCartTotal()
})
}
// Update Cart total price
function updateCartTotal() {
var cartItemContainer = document.getElementsByClassName('cart-items')[0]
var cartRows = cartItemContainer.getElementsByClassName('cart-info')
for (var i = 0; i < cartRows.length; i++) {
var cartRow = cartRows[i]
var priceElement = cartRow.getElementsByClassName('product-price')[0]
var quantityElement = cartRow.getElementsByClassName('quantity-value')
[0]
var price = parseFloat(priceElement.innerText.replace('R', ''))
var quantity = quantityElement.value
console.log(price * quantity)
}
}
<td>
<div class="cart-items">
<div class="cart-info">
<img src="images/men3(balenciaga).png" width="250px">
<span class="product-price">R7400</span>
</div>
<span class="cart-item-title">Balenciaga Speed High</span>
</div>
<br>
<button class="remove-btn" type="button">Remove</button>
</div>
</div>
</div>
</td>
<td><input class="quantity-value" type="number" value="1"></td>
</tr>
You are trying to get 'quantity-value' field inside cartRow, but it does not exist inside the 'cart-info' div, because of which you are getting this value as undefined.
var quantityElement = cartRow.getElementsByClassName('quantity-value')[0]
Your html should probably be like below:
var removeCartitemButtons = document.getElementsByClassName('remove-btn')
console.log(removeCartitemButtons)
for (var i = 0; i < removeCartitemButtons.length; i++) {
var button = removeCartitemButtons[i]
button.addEventListener('click', function(event) {
console.log('clicked')
var buttonClicked = event.target
buttonClicked.parentElement.remove()
// updateCartTotal()
})
}
<td>
<div class="cart-items">
<div class="cart-info">
<img src="images/men3(balenciaga).png" width="450px">
<span class="product-price">R7401</span>
<input class="quantity-value" type="number" value="1">
</div>
<span class="cart-item-title">Balenciaga Speed High1</span>
<button class="remove-btn" type="button">Remove1</button>
</div>
</td>
<td>
<div class="cart-items">
<div class="cart-info">
<img src="images/men3(balenciaga).png" width="450px">
<span class="product-price">R7402</span>
<input class="quantity-value" type="number" value="2">
</div>
<span class="cart-item-title">Balenciaga Speed High2</span>
<button class="remove-btn" type="button">Remove2</button>
</div>
</td>
<td>
<div class="cart-items">
<div class="cart-info">
<img src="images/men3(balenciaga).png" width="450px">
<span class="product-price">R7403</span>
<input class="quantity-value" type="number" value="3">
</div>
<span class="cart-item-title">Balenciaga Speed High3</span>
<button class="remove-btn" type="button">Remove3</button>
</div>
</td>

How to use localStorage in vanillaJS

I have 2 html pages which are for a laundry services website and I have a javascript file. The first html page is called booking page where user get to book the number of clothes to be washed and it automatically calculate the total amount to be paid. Now on the second html page which is the summary page, I want the same amount on the booking page to reflect on the summary page showing the total amount and also also the buttons (plus and minus button) adding to it in the summary page.
I tried using localStorage for this project and I couldn't figure it out.
Skirt(s)</p>
<div>
<p>
<button type="button" class="sub" data-
target="skirts">−</button>
<input type="text" value="0"
class="field_skirts" />
<button type="button" class="add" data-
target="skirts">+</button>
<p class="display_skirts" name="price"
max="3" min="1">₦ 0</p>
</p>
</div>
</div>
<div>
<div class="second-booking-container-image"><img
src="./img/blouse.png" /></div>
<p class="second-booking-container-icon"
name="product" value="100" id="qnty_4">
Blouse(s)</p>
<div>
<p>
<button type="button" class="sub" data-
target="blouses">-</button>
<input type="text" value="0"
class="field_blouses" />
<button type="button" class="add" data-
target="blouses">+</button>
<p class="display_blouses" name="price"
max="3" min="1">₦ 0</p>
</p>
</div>
</div>
<div>
<div class="second-booking-container-image"><img
src="./img/jacket.png" /></div>
<p class="second-booking-container-icon-long"
name="product" value="100" id="qnty_5">Suit/Jacket(s)
</p>
<p>
<button type="button" class="sub" data-
target="suits">-</button>
<input type="text" value="0" class="field_suits"
/>
<button type="button" class="add" data-
target="suits">+</button>
<p class="display_suits" name="price" max="3"
min="1">₦ 0</p>
</p>
</div>
</div>
<div class="third-booking-container">
<p>Total:₦ <span id="totalValue"></span></p>
<button>Set pick up date
<FontAwesomeIcon class="second-container-button-right"
icon="angle-right" /></button>
</div>
</div>
var subElm = document.querySelectorAll('.sub');
var addElm = document.querySelectorAll('.add');
var totalValueElm = document.getElementById('totalValue');
for (var i = 0; i < subElm.length; i++) {
subElm[i].addEventListener('click', function () {
var targetItem = this.getAttribute('data-target');
var inputElm = document.querySelector('.field_' + targetItem);
var displayElm = document.querySelector('.display_' +
targetItem);
var currentValue = +inputElm.getAttribute('value');
if (currentValue !== 0) {
var incValue = currentValue - 1;
var strValue = ' ' + incValue;
inputElm.setAttribute('value', incValue);
// displayElm.innerHTML = "₦" + strValue;
displayElm.innerHTML = "₦ " + incValue * 100;
totalValueElm.innerText = Number(totalValueElm.innerText) -
100;
}
});
addElm[i].addEventListener('click', function () {
var targetItem = this.getAttribute('data-target');
var inputElm = document.querySelector('.field_' + targetItem);
var displayElm = document.querySelector('.display_' +
targetItem);
var currentValue = +inputElm.getAttribute('value');
var incValue = currentValue + 1;
var strValue = ' ' + incValue;
inputElm.setAttribute('value', incValue);
// displayElm.innerHTML = "₦" + strValue;
displayElm.innerHTML = "₦ " + incValue * 100;
totalValueElm.innerText = Number(totalValueElm.innerText) + 100;
});
}
<div class="summaryContainer">
<div class="summaryNavBar"><p
className="summaryTitle">Summary</p></div>
<div class="summaryContent">
<p class="total" id="total">Total:</p>
<p class="sum">₦0.00</p>
</div>
<div class="summaryCard">
<div class="summary-card-title">
<div>Item</div>
<div>Quantity</div>
</div>
<div class="summary-card-content">
<div >Shirt(s)</div><div id="
first" class="summary-quantity"><button type="button"
id="sub" class="sub">−</button>
<input type="text" id="1" value="0" class="field" />
<button type="button" id="add" class="add">+</button>
</div>
</div>
<div class="summary-card-content">
<div>Trouser(s)</div>
<div class="summary-quantity" id="second">
<button type="button" id="sub" class="sub">−</button>
<input type="text" id="1" value="0" class="field" />
<button type="button" id="add" class="add">+</button>
</div>
</div>
<div class="summary-card-content" id="third">
I want the total calculation of price on the booking page to also appear at the summary page when I automatically click on summary page
In your booking page, store the total price in local storage using localStorage.setItem().
localStorage.setItem('totalPrice', JSON.stringify(totalValue));
In your summary page, access this total price using localStorage.getItem().
var totalPrice = JSON.parse(localStorage.getItem('totalPrice'));
Note that all the values are stored as strings, so you have to use JSON.parse() to convert the string back to the object or value.

Values in fields can not be recognized

why can not my function register a text that is clicked, but must I enter it manually to calculate in total?
Namely, my idea is that by clicking on a product, it is displayed in the input field [284] of the product price, and when clicking on a checkbox option to increase the price and display it at the end of [388], the text menu can now only it is compiled if I enter a number manually in field 285. How can I do it?
function displayAbo(el) {
document.getElementById("contactFormFieldId_284").value = el.querySelector('.product__title').textContent+ " " +el.querySelector('.product__price').textContent;
}
var checkBoxes = document.getElementsByClassName('contactFormClass_checkbox');
var sum = 0,
inputField = document.getElementById('contactFormFieldId_284'),
finalInput = document.getElementById('contactFormFieldId_388');
Array.prototype.slice.call(checkBoxes).forEach( (checkBox) => {
checkBox.addEventListener('change', calculateTotal, false);
})
inputField.addEventListener('blur', calculateSumWithInput, false);
function calculateTotal(e) {
if(e.target.checked) {
sum += parseInt(e.target.value, 10);
} else {
sum -= parseInt(e.target.value, 10);
}
finalInput.value ="CHF "+ sum + ".–";
}
function calculateSumWithInput(e) {
var re = /\d+/;
var value = re.exec(e.target.value);
if(value && !isNaN(value) && Number(value) === parseInt(value, 10)) {
sum = parseInt(value, 10);
finalInput.value = sum;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product__item" onclick="displayAbo(this)" id="product-medium" tabindex="-1" role="radio" aria-checked="false" aria-describedby="medium-desc">
<div class="product__inner" id="medium-desc">
<h3 class="product__title">LEUWIN M</h3>
<ul class="product__features">
<li class="product__features-item">40 Mbit/s</li>
<li class="product__features-item"><img src="themes/zuerich/images/I.png" style="width: 100px; margin-right: 110px;"></li>
</ul>
<h4 class="product__price">CHF 39.–</h4>
</div>
</div>
<div class="contact row">
<label for="contactFormFieldId_284" style="color: #003664; font-size: 16px; font-weight: bold;">[[284_LABEL]]</label>
<input class="contactFormClass_text" id="contactFormFieldId_284" type="text" name="contactFormField_284" value="[[284_VALUE]]" readonly />
</div>
<div class="contact row">
<label for="contactFormFieldId_385">[[385_LABEL]]</label>
<input class="contactFormClass_checkbox" id="contactFormFieldId_385" type="checkbox" name="contactFormField_385" value="5" [[SELECTED_385]] />
</div>
<div class="contact row">
<label for="contactFormFieldId_386">[[386_LABEL]]</label>
<input class="contactFormClass_checkbox" id="contactFormFieldId_386" type="checkbox" name="contactFormField_386" value="15" [[SELECTED_386]] />
</div>
<div class="contact row">
<label for="contactFormFieldId_387">[[387_LABEL]]</label>
<input class="contactFormClass_checkbox" id="contactFormFieldId_387" type="checkbox" name="contactFormField_387" value="20" [[SELECTED_387]] />
</div>
<div class="contact row">
<label for="contactFormFieldId_388" style="color: #003664; font-size: 16px; font-weight: bold;">[[388_LABEL]]</label>
<input class="contactFormClass_text" id="contactFormFieldId_388" type="text" name="contactFormField_388" value="0" />
</div>
I have made 2 changes.
Changed your blur function to click
inputField.addEventListener('click', calculateSumWithInput, false);
Added click triggers in your functions
inputField.click();
function displayAbo(el) {
document.getElementById("contactFormFieldId_284").value = el.querySelector('.product__title').textContent + " " + el.querySelector('.product__price').textContent;
inputField.click();
}
var checkBoxes = document.getElementsByClassName('contactFormClass_checkbox');
var sum = 0,
inputField = document.getElementById('contactFormFieldId_284'),
finalInput = document.getElementById('contactFormFieldId_388');
Array.prototype.slice.call(checkBoxes).forEach((checkBox) => {
checkBox.addEventListener('change', calculateTotal, false);
})
inputField.addEventListener('click', calculateSumWithInput, false);
inputField.click();
function calculateTotal(e) {
if (e.target.checked) {
sum += parseInt(e.target.value, 10);
} else {
sum -= parseInt(e.target.value, 10);
}
finalInput.value = "CHF " + sum + ".–";
}
function calculateSumWithInput(e) {
var re = /\d+/;
var value = re.exec(e.target.value);
if (value && !isNaN(value) && Number(value) === parseInt(value, 10)) {
sum = parseInt(value, 10);
finalInput.value = "CHF " + sum + ".–";
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product__item" onclick="displayAbo(this)" id="product-medium" tabindex="-1" role="radio" aria-checked="false" aria-describedby="medium-desc">
<div class="product__inner" id="medium-desc">
<h3 class="product__title">LEUWIN M</h3>
<ul class="product__features">
<li class="product__features-item">40 Mbit/s</li>
<li class="product__features-item"><img src="themes/zuerich/images/I.png" style="width: 100px; margin-right: 110px;"></li>
</ul>
<h4 class="product__price">CHF 39.–</h4>
</div>
</div>
<div class="contact row">
<label for="contactFormFieldId_284" style="color: #003664; font-size: 16px; font-weight: bold;">[[284_LABEL]]</label>
<input class="contactFormClass_text" id="contactFormFieldId_284" type="text" name="contactFormField_284" value="[[284_VALUE]]" readonly />
</div>
<div class="contact row">
<label for="contactFormFieldId_385">[[385_LABEL]]</label>
<input class="contactFormClass_checkbox" id="contactFormFieldId_385" type="checkbox" name="contactFormField_385" value="5" [[SELECTED_385]] />
</div>
<div class="contact row">
<label for="contactFormFieldId_386">[[386_LABEL]]</label>
<input class="contactFormClass_checkbox" id="contactFormFieldId_386" type="checkbox" name="contactFormField_386" value="15" [[SELECTED_386]] />
</div>
<div class="contact row">
<label for="contactFormFieldId_387">[[387_LABEL]]</label>
<input class="contactFormClass_checkbox" id="contactFormFieldId_387" type="checkbox" name="contactFormField_387" value="20" [[SELECTED_387]] />
</div>
<div class="contact row">
<label for="contactFormFieldId_388" style="color: #003664; font-size: 16px; font-weight: bold;">[[388_LABEL]]</label>
<input class="contactFormClass_text" id="contactFormFieldId_388" type="text" name="contactFormField_388" value="0" />
</div>

how to make progress bar value increase according to entered number

I have an input and progress bar.
I need to enter a number (%) and display the value in the progress bar after clicking button (btn-primary).
Here is my HTML:
<div class="form-group">
<label for="number">Введите число!</label>
<input type="text" class="form-control" id="number" min="0" max="100" required>
</div>
<button type="button" class="btn btn-primary">Применить</button>
<div class="progress-wrap">
<div class="progress-message">Ваша форма заполнена на <span class="output">___</span> %</div>
<progress max="100" value="0" class="progress"></progress>
</div>
I tried to write a script, but I doesn't work.
var val = document.querySelector('.form-controll').value;
var btn = document.querySelector('.btn-primary');
var progress = document.querySelector('.progress');
btn.addEventListener('click, displayData');
function displayData() {
progress.attr('value', val);
progress.style.background = 'green';
}
Here is a link to codepen:
https://codepen.io/ksena19/pen/QVRNep
I edited your code
you can check it out here: https://codepen.io/anon/pen/rZgLyq
HTML:
<div class="form-group">
<label for="number">Введите число!</label>
<input type="text" class="form-control" id="number" min="0" max="100" required>
</div>
<button id="btn" type="button" class="btn btn-primary">Применить</button>
<div class="progress-wrap">
<div class="progress-message">Ваша форма заполнена на <span class="output">___</span> %</div>
<progress max="100" value="0" class="progress"></progress>
</div>
JS:
$(document).ready(function(){
$('#btn').click(function(){
var val = $('#number').val();
est(val);
});
});
function est(value) {
var progress = $(".progress"),
progressMessage = $(".progress-message");
if (value == 0) {
progress.attr("value", "0");
progressMessage.text("Complete the form.");
}
if (value == 1) {
progress.attr("value", "33");
progressMessage.text("There you go, great start!");
progress.addClass('light-green');
}
if (value == 2) {
progress.attr("value", "66");
progressMessage.text("Nothing can stop you now.");
progress.addClass('green');
}
if (value == 3) {
progress.attr("value", "100");
progressMessage.text("Completed!");
progress.addClass('dark-green');
}
}
You have used HTML tag. This tag is working based on value="0" attribute. If value=0 means, there is no progress.
Below, I have added an exact code. If we enter the number in the particular textbox, the progress bar will be reacted based on a number value. You can able to run the below code directly.
<script type="text/javascript">
function count(){
var getNum = document.getElementById("number");
document.getElementById("progress").setAttribute("value", getNum);
}
</script>
<!-- Progress bar -->
<div class="form-group">
<label for="number">Введите число!</label>
<input type="text" class="form-control" id="number" min="0" max="100" required>
</div>
<button type="button" class="btn btn-primary" onClick="count();">Применить</button>
<div class="progress-wrap">
<div class="progress-message">Ваша форма заполнена на <span class="output">___</span> %</div>
<progress max="100" value="0" class="progress" id="progress"></progress>
</div>
I created sample page which takes input and shows progress after clicking on button.
HTML code including style and JavaScript function:
<html>
<style>
#myProgress {
width: 100%;
background-color: #ddd;
}
#myBar {
width: 0%;
height: 30px;
background-color: #4CAF50;
text-align: center;
line-height: 30px;
color: white;
}
</style>
<body>
<div id="myProgress">
<div id="myBar">0%</div>
</div>
<br>
<input type="text" class="form-control" id="number" min="0" max="100" required>
<button type="button" onclick="change_progress()">Change Progress</button>
</body>
</html>
<script>
function change_progress() {
var elem = document.getElementById("myBar");
val = parseInt(document.getElementById("number").value);
var width = 0;
var id = setInterval(frame, val);
function frame() {
if (width >= val) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
elem.innerHTML = width * 1 + '%';
}
}
}
</script>
Edited your js as below:
var btn = $('.btn-primary');
var progress = $('.progress');
btn.click(function(){
var value = Number($('.form-control').val());
progress.attr('value', progress.val() + value);
});
.progress {
width: 20%;
height: 20px;
margin: 0 0 5px 0;
background: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label for="number">Введите число!</label>
<input type="text" class="form-control" id="number" min="0" max="100" required>
</div>
<button type="button" class="btn btn-primary">Применить</button>
<div class="progress-wrap">
<div class="progress-message">Ваша форма заполнена на <span class="output">___</span> %</div>
<progress max="100" value="0" class="progress"></progress>
</div>

Change count JavaScript function

Currently, this function seems to count all the way to the higher value. I want it to simply count to the lower value of 30.
This is the script:
$(".circleStatsItemBox").each(function() {
var value = $(this).find(".value > .number").html();
var unit = $(this).find(".value > .unit").html();
var percent = $(this).find("input").val() / 100;
countSpeed = 2300 * percent;
endValue = value;
$(this).find(".count > .unit").html(unit);
$(this).find(".count > .number").countTo({
from: 0,
to: endValue,
speed: countSpeed,
refreshInterval: 50
});
//$(this).find(".count").html(value*percent + unit);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/mhuggins/jquery-countTo/master/jquery.countTo.js"></script>
<div class="circleStatsItemBox yellow">
<div class="header">Levels of Interest</div>
<span class="percent">% Increase</span>
<div class="circleStat">
<input value="25" class="whiteCircle" type="text">
</div>
<div class="footer"><span class="count">
<span class="number">30</span>
<span class="unit">Before</span>
</span> <span class="sep"> / </span>
<span class="value">
<span class="number">40</span>
<span class="unit"> During</span>
</span>
</div>
</div>
You need to change a selector in the JavaScript code.
var value = $(this).find(".count > .number").html();
$(".circleStatsItemBox").each(function() {
var value = $(this).find(".count > .number").html();
var unit = $(this).find(".value > .unit").html();
var percent = $(this).find("input").val() / 100;
countSpeed = 2300 * percent;
endValue = value;
$(this).find(".count > .unit").html(unit);
$(this).find(".count > .number").countTo({
from: 0,
to: endValue,
speed: countSpeed,
refreshInterval: 50
});
//$(this).find(".count").html(value*percent + unit);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/mhuggins/jquery-countTo/master/jquery.countTo.js"></script>
<div class="circleStatsItemBox yellow">
<div class="header">Levels of Interest</div>
<span class="percent">% Increase</span>
<div class="circleStat">
<input value="25" class="whiteCircle" type="text">
</div>
<div class="footer">
<span class="count">
<span class="number">30</span>
<span class="unit">Before</span>
</span>
<span class="sep"> / </span>
<span class="value">
<span class="number">40</span>
<span class="unit"> During</span>
</span>
</div>
</div>

Categories