<pre>
<div class="quantity">
<input type="number" name="qty" id="qty" value="1" class="form-qty form-control" min="1">
<div class="quantity-nav">
<div class="quantity-button quantity-up qty-up">+</div>
<div class="quantity-button quantity-down qty-down">-</div>
</div>
</div>
<pre>
This is loop.
I want to get input value when i click quantity up & down button each time. There are multiple elements.
How to find input value in javascript by clicking button up & down.
You can add onClick event with parents feature to detect the inputs near to the button.
$(document).on('click','.quantity-up',function(){
$qtyElemnt = $(this).parents('.quantity').find('.form-qty');
$qty = $qtyElemnt.val();
$qtyElemnt.val(Number($qty)+1);
});
$(document).on('click','.quantity-down',function(){
$qtyElemnt = $(this).parents('.quantity').find('.form-qty');
$qty = $qtyElemnt.val();
$qtyElemnt.val(Number($qty)-1);
});
.quantity {
padding: 10px;
}
.quantity-nav{
display: inline-block;
}
.quantity-button {
display: inline-block;
padding: 5px;
background-color: #c7c5c5;
border: 1px solid #585353;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<div class="quantity">
<input type="number" name="qty" value="1" class="form-qty form-control" min="1">
<div class="quantity-nav">
<div class="quantity-button quantity-up qty-up">+</div>
<div class="quantity-button quantity-down qty-down">-</div>
</div>
</div>
<div class="quantity">
<input type="number" name="qty" value="1" class="form-qty form-control" min="1">
<div class="quantity-nav">
<div class="quantity-button quantity-up qty-up">+</div>
<div class="quantity-button quantity-down qty-down">-</div>
</div>
</div>
<div class="quantity">
<input type="number" name="qty" value="1" class="form-qty form-control" min="1">
<div class="quantity-nav">
<div class="quantity-button quantity-up qty-up">+</div>
<div class="quantity-button quantity-down qty-down">-</div>
</div>
</div>
</div>
Thanks :-)
Actually your problem is quite easy to solve.
Try to add this script at the end of your <body>.
I suggest you to make some modifications in your html too: use <button> or <input type="button"or even <a> tags for your controls.
I added some logic about the min/max/step attributes you can set on a <input type="number"> but this is optional. It's up to you to change this.
document.addEventListener("DOMContentLoaded", function() {
const qtyWraps = document.getElementsByClassName('quantity');
for (let i = 0; i < qtyWraps.length; i++) {
const qtyWrap = qtyWraps.item(i);
const input = qtyWrap.querySelector('.form-qty');
const up = qtyWrap.querySelector('.qty-up');
const down = qtyWrap.querySelector('.qty-down');
const output = qtyWrap.querySelector('.output');
up.addEventListener('click', function(e) {
e.preventDefault();
addValue(1);
});
down.addEventListener('click', function(e) {
e.preventDefault();
addValue(-1);
});
input.addEventListener('input', function() {
output.textContent = input.value
});
const addValue = function(value) {
const current = parseInt(input.value);
const min = input.getAttribute('min') || -Infinity;
const max = input.getAttribute('max') || Infinity;
const step = input.getAttribute('step') || 1;
const newValue = Math.min(max, Math.max(min, current + value * step));
input.value = newValue;
if (newValue <= min) down.setAttribute('disabled', 'disabled');
else down.removeAttribute('disabled');
if (newValue >= max) up.setAttribute('disabled', 'disabled');
else up.removeAttribute('disabled');
input.dispatchEvent(new Event('input'));
}
addValue(0)
}
});
.quantity {
display: block;
width: 500px;
margin: auto;
text-align: center;
}
.quantity .form-qty {
display: inline-block;
}
.quantity .quantity-nav {
display: inline-block;
}
.quantity .output {
background: yellow;
width: 500px;
margin: 1em auto 0;
}
<div class="quantity">
<input type="number" name="qty" id="qty" value="1" class="form-qty form-control" min="1">
<div class="quantity-nav">
<button class="quantity-button quantity-up qty-up">+</button>
<button class="quantity-button quantity-down qty-down">-</button>
</div>
<!-- I put it here to show the output result -->
<div class="output">1</div>
</div>
You can use localStorage to store the value of your quantity, this would make the data persistent.
Please check the below code snippet:
const down = document.querySelector('.down');
const up = document.querySelector('.up');
const input = document.querySelector('.quantity');
// store utility function
const store = {
existsIn: function(key) {
return this.getFromKey(key) !== null;
},
getFromKey: function(key) {
return window.localStorage.getItem(key);
},
add: function(key, value) {
const storeSource = window.localStorage.setItem(key, value);
}
}
const quantity = Object.create(store);
quantity.exists = function() {
return this.existsIn('quantity');
}
quantity.increase = function() {
let storedQuantity = this.exists() ? parseFloat(this.getFromKey('quantity')) : 0;
storedQuantity = storedQuantity + 1;
this.add('quantity', storedQuantity);
}
quantity.decrease = function() {
let storedQuantity = this.exists() ? parseFloat(this.getFromKey('quantity')) : 0;
if(storedQuantity > 0) {
storedQuantity = storedQuantity - 1;
}
this.add('quantity', storedQuantity);
}
quantity.show = function() {
return this.exists() ? this.getFromKey('quantity') : 0;
}
// event listeners for up and down buttons
up.addEventListener('click', function() {
quantity.increase();
// update input on button click
input.value = quantity.show();
})
down.addEventListener('click', function() {
quantity.decrease();
// update input on button click
input.value = quantity.show();
})
// update input on page load
input.value = quantity.show();
There you can find a working fiddle:
https://jsbin.com/tavalocoti/5/edit?html,js,console,output
Related
i want to have multiple elements with same class that act independently, after 1 night of seeking if "forEach" has any 'forEach:active' i end up with code below, but i feel kind of little shame with 'nextSibling of parent of parent' but if is supported by atleast any modern browsers, then is better than nothing.
on codePen is working fine,as well as snippet here.
i wonder if i can find a better version in vanila js for it or if is there anything deprecated that i should change.
//get + button
const up = document.querySelectorAll('.up');
//tell to + to increase his previous frend value
[].forEach.call(up, function(element) {
element.addEventListener('click', function() {
this.previousElementSibling.value =
parseInt(this.previousElementSibling.value) + 1;
});
})
//get -
const down = document.querySelectorAll('.down');
//tell to - to decrease his next frend value && and hide
//dynamic
//input if == 0 && show firstAdd button
[].forEach.call(down, function(element) {
element.addEventListener('click', function() {
this.nextElementSibling.value =
parseInt(this.nextElementSibling.value) - 1;
if (this.nextElementSibling.value == 0) {
this.parentElement.parentElement.style.display = 'none';
this.parentElement.parentElement.nextElementSibling.style.display = 'initial';
}
});
})
//get firstAdd button
const fAdd = document.querySelectorAll('.firstAdd');
//tell to it to add dynamic input && to vanish itself after &&
//set input value = 1
[].forEach.call(fAdd, function(element) {
element.addEventListener('click', function() {
this.previousElementSibling.style.display = 'initial';
this.previousElementSibling.children[1].children[1].value = 1;
this.style.display = 'none'
});
})
.form-group {
width: 30%;
margin: 30px;
display: none;
}
.input-group {
flex-direction: row;
display: flex;
}
body {
background: #111;
}
<div class='one'>
<div class="form-group">
<label>value: </label>
<div class="input-group">
<button class="down">-</button>
<input type="text" class="myNumber" value='1'>
<button class="up">+</button>
</div>
</div>
<button class='firstAdd'>Add</button></div>
<br>
<div class='two'>
<div class="form-group">
<label>value: </label>
<div class="input-group">
<button class="down">-</button>
<input type="text" class="myNumber" value='1'>
<button class="up">+</button>
</div>
</div>
<button class='firstAdd'>Add</button></div>
I have to get the value of .qty input field but I have a problem that another jQuery function is rewriting the entered value after it gets entered.
For instance, if I enter 1, it gets rounded to 3,3360 but multiplied by 1 so I only can get the written value but I need the value that is changed after (3,3360) and the result should be 33.36 not 10.00:
function myFunctionupdateqtyinput() {
var x = document.getElementById("quantity_60269d6f09cd1");
var a = 3.336;
var b = x.value;
var d = b - (b % a) + a;
var f = d.toPrecision(5);
x.value = f;
}
if ($(".kpt-product-count").length) {
function checkForCount() {
var single_count = parseFloat($(".kpt-product-count").data('kptcount'));
var qty = parseFloat($(".qty").val());
var total = (qty * single_count);
total = total.toFixed(2);
if (isNaN(total)) {
total = single_count.toFixed(2);
}
$(".kpt-product-count-text").find('span').html(total);
}
$(".qty").on('input', checkForCount);
}
#import url("https://tonicuk.com/wp-content/plugins/woocommerce/assets/css/woocommerce-layout.css");
#import url("https://tonicuk.com/wp-content/plugins/woocommerce/assets/css/woocommerce-smallscreen.css");
#import url("https://tonicuk.com/wp-content/plugins/woocommerce/assets/css/woocommerce.css");
.quantity .qty {
height: 34px;
}
.quantitym2 .qty {
width: 90;
margin-right: 10;
}
.kpt-product-count {
display: inline-flex;
font-size: 15px;
margin-top: 15px;
}
.kpt-product-count-label {
font-weight: 600;
padding-right: 10px;
}
.quantitym2 input::-webkit-inner-spin-button {
display: none !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="quantity quantitym2">
<label class="screen-reader-text" for="quantity_60269d6f09cd1">Boost quantity</label>
<input type="number" onchange="myFunctionupdateqtyinput()" id="quantity_60269d6f09cd1" class="input-text qty text" value="3.336" step="0.0001" min="0.0001" max="" name="quantity" title="title" size="4" placeholder="" inputmode="">
</div>
<div class="kpt-product-count" data-kptcount="10">
<div class='kpt-product-count-label'>In total: </div>
<div class='kpt-product-count-text'> <span>10</span> </div>
</div>
You need to call the function myFunctionupdateqtyinput()inside the checkForCount function
function checkForCount() {
myFunctionupdateqtyinput();
function myFunctionupdateqtyinput() {
var x = document.getElementById("quantity_60269d6f09cd1");
var a = 3.336;
var b = x.value;
var d = b - (b % a) + a;
var f = d.toPrecision(5);
x.value = f;
}
if ($(".kpt-product-count").length) {
function checkForCount() {
myFunctionupdateqtyinput();
var single_count = parseFloat($(".kpt-product-count").data('kptcount'));
var qty = parseFloat($(".qty").val());
var total = (qty * single_count);
total = total.toFixed(2);
if (isNaN(total)) {
total = single_count.toFixed(2);
}
$(".kpt-product-count-text").find('span').html(total);
}
$(".qty").on('input', checkForCount);
}
#import url("https://tonicuk.com/wp-content/plugins/woocommerce/assets/css/woocommerce-layout.css");
#import url("https://tonicuk.com/wp-content/plugins/woocommerce/assets/css/woocommerce-smallscreen.css");
#import url("https://tonicuk.com/wp-content/plugins/woocommerce/assets/css/woocommerce.css");
.quantity .qty {
height: 34px;
}
.quantitym2 .qty {
width: 90;
margin-right: 10;
}
.kpt-product-count {
display: inline-flex;
font-size: 15px;
margin-top: 15px;
}
.kpt-product-count-label {
font-weight: 600;
padding-right: 10px;
}
.quantitym2 input::-webkit-inner-spin-button {
display: none !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="quantity quantitym2">
<label class="screen-reader-text" for="quantity_60269d6f09cd1">Boost quantity</label>
<input type="number" onchange="myFunctionupdateqtyinput()" id="quantity_60269d6f09cd1" class="input-text qty text" value="3.336" step="0.0001" min="0.0001" max="" name="quantity" title="title" size="4" placeholder="" inputmode="">
</div>
<div class="kpt-product-count" data-kptcount="10">
<div class='kpt-product-count-label'>In total: </div>
<div class='kpt-product-count-text'> <span>10</span> </div>
</div>
this is my script to add input fields dynamically, in this part, the max of fields is 10.
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 1;
$(add_button).click(function(e) {
e.preventDefault();
if (x < max_fields) {
x++;
var form_colis = '<div><input type="text" placeholder="Poids" name="poids[]"/> <input type="text" placeholder="Longueur" name="longueurs[]"/> <input type="text" placeholder="Largeur" name="largeurs[]"/> <input type="text" placeholder="Hauteur" name="hauteurs[]"/>Delete</div>';
//$(wrapper).append('<div><input type="text" name="mytext[]"/>Delete</div>'); //add input box
$(wrapper).append(form_colis); //add input box
} else {
alert('You Reached the limits')
}
});
$(wrapper).on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container1">
<button class="add_form_field">Add New Field
<span style="font-size:16px; font-weight:bold;">+ </span>
</button>
<div>
<input type="text" placeholder="Poids" name="poids[]">
<input type="text" placeholder="Longueur" name="longueurs[]">
<input type="text" placeholder="Largeur" name="largeurs[]">
<input type="text" placeholder="Hauteur" name="hauteurs[]">
</div>
</div>
Now, I want to add fields in function of the sum of previous fields name. eg. for fields name poids[], if the sum is higher than 100, the user can't add fieldset, else, he can.
I hope that you understand what I mean.
thank you in advance
Here is a version that will calculate. I made the code shorter too - please note the CSS changes and the added class to item div
I assume you only want to test that poids > 100 ?
$(function() {
var max_fields = 10;
var $wrapper = $(".container1");
var add_button = $(".add_form_field");
$(add_button).click(function(e) {
e.preventDefault();
const vals = $("> .item input[name^=poids]",$wrapper).map(function() { return +this.value }).get()
const val = vals.length === 0 ? 0 : vals.reduce((a, b) => a + b);
if ($("> .item",$wrapper).length < max_fields && val < 100) {
const $form_colis = $(".item").first().clone();
$form_colis.find("input").val("");
$wrapper.append($form_colis); //add input box
} else {
alert('You Reached the limits')
}
});
$wrapper.on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
})
});
.container1 .item:first-of-type .delete {
display: none;
}
.delete { text-decoration: none; color: red; }
.add_form_field { white-space: nowrap; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="add_form_field">Add New Field ✚</button>
<div class="container1">
<div class="item">
<input type="text" placeholder="Poids" name="poids[]">
<input type="text" placeholder="Longueur" name="longueurs[]">
<input type="text" placeholder="Largeur" name="largeurs[]">
<input type="text" placeholder="Hauteur" name="hauteurs[]">
Delete
</div>
</div>
If I understood your problem correctly, then check this solution, modified by me. If the sum of all fields is exactly less than 100, then new fields are added, otherwise they are not added. Was it necessary?
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 1;
$(add_button).click(function(e) {
e.preventDefault();
$('.inputs:last-of-type').each(function(){
var sum_inputs = 0;
$(this).find('input').each(function(){
sum_inputs += parseInt($(this).val());
});
if (x < max_fields && sum_inputs < '100') {
x++;
var form_colis = '<div class="inputs"><input type="text" placeholder="Poids" name="poids[]"/> <input type="text" placeholder="Longueur" name="longueurs[]"/> <input type="text" placeholder="Largeur" name="largeurs[]"/> <input type="text" placeholder="Hauteur" name="hauteurs[]"/>Delete</div>';
//$(wrapper).append('<div><input type="text" name="mytext[]"/>Delete</div>'); //add input box
$(wrapper).append(form_colis); //add input box
} else {
alert('You Reached the limits')
}
});
});
$(wrapper).on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container1">
<button class="add_form_field">Add New Field
<span style="font-size:16px; font-weight:bold;">+ </span>
</button>
<div class="inputs">
<input type="text" placeholder="Poids" name="poids[]">
<input type="text" placeholder="Longueur" name="longueurs[]">
<input type="text" placeholder="Largeur" name="largeurs[]">
<input type="text" placeholder="Hauteur" name="hauteurs[]">
</div>
</div>
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>
I am using - and + buttons to change the number of the text box, I am having troubles dealing with different text fields, here is my code:
var unit = 0;
var total;
// if user changes value in field
$('.field').change(function() {
unit = this.value;
});
$('.add').click(function() {
unit++;
var $input = $(this).prevUntil('.sub');
$input.val(unit);
unit = unit;
});
$('.sub').click(function() {
if (unit > 0) {
unit--;
var $input = $(this).nextUntil('.add');
$input.val(unit);
}
});
button {
margin: 4px;
cursor: pointer;
}
input {
text-align: center;
width: 40px;
margin: 4px;
color: salmon;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id=field1>
field 1
<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 id=field2>
field 2
<button type="button" id="sub2" class=sub>-</button>
<input type="text" id="2" value=0 class=field>
<button type="button" id="add2" class=add>+</button>
</div>
And here's the DEMO
You can see in the demo that the values change correctly only if you click buttons on the same field, but if you alternate between fields the values don't change properly.
This should be all you need:
$('.add').click(function () {
$(this).prev().val(+$(this).prev().val() + 1);
});
$('.sub').click(function () {
if ($(this).next().val() > 0) $(this).next().val(+$(this).next().val() - 1);
});
By using the unit variable you were tying both inputs together. And the plus in +$(this) is a shorthand way to take the string value from the input and convert it to a number.
jsFiddle example
You're using the same variable to hold the values of your two inputs. One simple option would be to use two variables instead of one:
var unit_1 = 0;
$('#add1').click(function() {
unit_1++;
var $input = $(this).prev();
$input.val(unit_1);
});
/* Same idea for sub1 */
var unit_2 = 0;
$('#add2').click(function() {
unit_2++;
var $input = $(this).prev();
$input.val(unit_2);
});
/* Same idea for sub2 */
and unit = unit just assigns the value of unit to itself, so that's no very useful and you can certainly leave it out.
An alternative approach is to use data attributes and have each element store its own value. Edit: it already stores its own value. Just access it.
var total;
// if user changes value in field
$('.field').change(function() {
// maybe update the total here?
}).trigger('change');
$('.add').click(function() {
var target = $('.field', this.parentNode)[0];
target.value = +target.value + 1;
});
$('.sub').click(function() {
var target = $('.field', this.parentNode)[0];
if (target.value > 0) {
target.value = +target.value - 1;
}
});
button {
margin: 4px;
cursor: pointer;
}
input {
text-align: center;
width: 40px;
margin: 4px;
color: salmon;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id=field1>
field 1
<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 id=field2>
field 2
<button type="button" id="sub2" class=sub>-</button>
<input type="text" id="2" value=0 class=field>
<button type="button" id="add2" class=add>+</button>
</div>