If I have few on my form. How can I access to input what I need?
<label> First </label>
<input type="number" value="1" min="1">
<label>22</label>
<span>There I need value in input * val in label</span>
<label> Second </label>
<input type="number" value="1" min="1">
<label>12</label>
<span>There I need value in input * val in label</span>
................................
How can I do this? Maybe I need to use loop?
Not sure exactly which input you are trying to access.
You can use document.querySelectorAll("input[type=number]").
It will return an array with all inputs of type "number". Iterate through them to get what you need
You can use for loop to loop all inputs and addEventListener to run function on input change. Then just calculate value for each input and add to span as textContent.
var inputs = document.querySelectorAll('input');
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener('change', function() {
var val = this.value * Number(this.nextElementSibling.textContent);
this.nextElementSibling.nextElementSibling.textContent = val;
})
}
<label>First</label>
<input type="number" value="1" min="1">
<label>22</label>
<span>There I need value in input * val in label</span>
<label>Second</label>
<input type="number" value="1" min="1">
<label>12</label>
<span>There I need value in input * val in label</span>
If you want to add values to spans even before input change you can add this part of code to previous one.
var inputs = document.querySelectorAll('input');
for (var i = 0; i < inputs.length; i++) {
var val = inputs[i].value * Number(inputs[i].nextElementSibling.textContent);
inputs[i].nextElementSibling.nextElementSibling.textContent = val;
inputs[i].addEventListener('change', function() {
var val = this.value * Number(this.nextElementSibling.textContent);
this.nextElementSibling.nextElementSibling.textContent = val;
})
}
<label>First</label>
<input type="number" value="1" min="1">
<label>22</label>
<span>There I need value in input * val in label</span>
<label>Second</label>
<input type="number" value="1" min="1">
<label>12</label>
<span>There I need value in input * val in label</span>
You can add an id to the controls and then access it using jquery by the id.
<label> First </label>
<input type="number" value="1" min="1" id="input1">
<label id="label1">22</label>
<span id="span1">There I need value in input * val in label</span>
<label> Second </label>
<input type="number" value="1" min="1" id="input2">
<label id="label2">12</label>
<span id="span2">There I need value in input * val in label</span>
Then on your dcoument.ready just calculate it like this:
$( document ).ready(function() {
var result1=$(#input1).val()*$(#label1).val();
$('#span1').val(result1);
var result2=$(#input2).val()*$(#label2).val();
$('#span1').val(result2);
});
After you gave an id to the controls you can do it even nicer, looping through all the inputs an dynamically multiply them:
var i=0;
$("#myForm input[type=text]").each(function() {
i=i+1;
$('#span'+i).val($('#input'+i)*('#label'+i));
});
Related
Using a solution from a relevant question, how can I use the following script to only work on a specific input by limiting the input range between 0 and 0.20? For example, I have two number inputs with the ID's "A" and "B", and I only want the following script to work on input id="A".
$('input').on('input', function () {
var value = this.value;
if (value !== '') {
value = parseFloat(value);
if (value < 0)
this.value = 0;
else if (value > 0.20)
this.value = 0.20;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="a" value="0" />
<input type="number" id="b" value="0" />
Use the ID of the specific element.
$('#a').on('input', function () {
Demo:
$('#a').on('input', function() {
var value = this.value;
if (value !== '') {
value = parseFloat(value);
if (value < 0)
this.value = 0;
else if (value > 0.20)
this.value = 0.20;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="a" value="0" />
<input type="number" id="b" value="0" />
Alternatively, if you only need to support HTML5-compatible browsers you could ditch the JavaScript and simply use min and max attributes on the element itself. You can also use step to control how much the button increases the value by, which makes sense in a scenario where the input range is so small:
<input type="number" id="a" value="0" min="0" max="0.2" step="0.1" />
<input type="number" id="b" value="0" />
Change the selector from selecting all inputs to just the one you want e.g. $('#a').on('input', ...
I'm building a multiple quantity selector for my store. Image below:
On the site, the price of the product updates based on the quantity added. 10 products = 10% off etc. I'd like to be able to display this price change as and when the user edits any one of the input boxes in the quantity selector.
The input fields are built like this:
<div data-value="S" data-varientid="8195426353207" class="swatch-element swatch-element-2 size s available">
<input id="swatch-0-s" data-variant-id="variant_8195426353207" type="checkbox" name="option-0" value="S">
<label for="swatch-0-s">
S
<img class="crossed-out" src="//cdn.shopify.com/s/files/1/0020/2188/3959/t/2/assets/soldout.png?5180939831627851747" alt="">
</label>
<input id="qty" name="quantity" class="swatchinput" placeholder="0" value="0" type="text">
</div>
I'm able to watch the input boxes for change by doing the below:
var qty = $('.swatchinput');
$('.swatchinput').on('paste keyup', function() {
console.log(qty);
});
However, this returns the information about the element rather than the contents. I'm also unsure of the best way to then add the contents of the various input fields together to reach the total quantity.
You could also use the Array reduce method to do this. Select all the inputs, get the array, then reduce their values into the sum.
var total = $('.swatchinput').get().reduce(function(total, input){
return total + parseInt(input.value || '0');
}, 0);
console.log(total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="quantity" class="swatchinput" placeholder="0" value="1" type="text">
<input name="quantity" class="swatchinput" placeholder="0" value="2" type="text">
<input name="quantity" class="swatchinput" placeholder="0" value="3" type="text">
<input name="quantity" class="swatchinput" placeholder="0" value="4" type="text">
This needs to be
var qty = $('.swatchinput').val();
not
var qty = $('.swatchinput');
As for your second question,
loop each of these inputs, getting the value, then add them up with a total. Initialize the total OUTSIDE of the loop also so it doesn't overwrite it.
Something like this?
var total = 0;
$('.switchinput').each(function(){
total += $(this).val();
});
console.log(total);
To get the value of an element in jQuery, use .val():
http://api.jquery.com/val/
.each loops through each matched element and runs a function on that element (accessible through 'this')
http://api.jquery.com/each/
i need sum of (every check box value X its textbox value)
<input name="33" value="280000" onclick="test(this);" type="checkbox">
<input id="33" style="width:20px;float: left; text-align: center" type="text">
example:
fist checkbox value = 20 X its textbox value = 10
second checkbox value = 5 X its textbox value = 2
my answer = 20*10 + 5*2 = 210 (ok)
also i need when checkbox value changes my answer change, without click.
const totalBox = document.getElementById("total")
document.querySelectorAll("input[type=text]").forEach((input) => input.addEventListener("input", calculate))
document.querySelectorAll("input[type=checkbox]").forEach((input) => input.addEventListener("change", calculate))
function calculate() {
const checkboxes = document.querySelectorAll("input[type=checkbox]")
let total = 0
for (let checkbox of checkboxes) {
if (checkbox.checked) {
total += Number(checkbox.value) * Number(document.getElementById(checkbox.name).value)
}
}
totalBox.textContent = total
}
calculate()
<input name="33" value="280000" type="checkbox" checked>
<input id="33" value="10" type="text">
<br/>
<input name="34" value="150000" type="checkbox">
<input id="34" value="15" type="text">
<h2>Total: <span id="total"></span></h2>
Here you go with the solution https://jsfiddle.net/yuhpbz47/
var total = 0;
$('button[type="submit"]').click(function(){
$('input[type="checkbox"]').each(function(){
if($(this).is(':checked')){
total += $(this).val() * (parseInt($(this).next().val()) || 0 );
}
});
console.log(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="10" />
<input type="text" />
<br/>
<input type="checkbox" value="20"/>
<input type="text" />
<button type="submit">
Submit
</button>
If they are always grouped by two you can simply take all inputs, multiply every pairs value and add it up:
var result = Array.from(document.getElementsByTagName("input")).reduce(function(result,el,i,arr){
return result+i%2?el.value*(arr[i-1].checked?arr[i-1].value:0):0;
},0);
for shure this can be executed inside an onchange handler.
http://jsbin.com/muvigedodu/edit?js
You are trying to achieve, when a check box is clicked a value is multiplied by the value of the input check box then for all check box give us the sum right? if so this below code which is well documented should help out with it
Observe the pattern i used to get the multiply value so it can be dynamic
Hope it helps.
$(document).ready(
function(){
/**
* this is used to update our view so you see what we are * doing currently now
*/
function updateView(value){
$("#view").html(value);
}
$(".sum").click(function(event){
//we get our value to multiply our value with
var multiply = $(this).attr("multiply");
var value = $(this).val();
//we multiply here
var answer = multiply*value;
//we sum up this value with the sum in the hidden fied if checked else substract
var sumField = $("#sum");
if($(this).is(':checked')){
sumField.val(Number(sumField.val())+answer);
}else{
sumField.val(Number(sumField.val())-answer);
}
//update our view
updateView(sumField.val());
});
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Check boxes
<br>
1. <input type="checkbox" value="10" multiply="20" class="sum"> value 10, multiply 20 <br>
2. <input type="checkbox" value="5" multiply="10" class="sum"> value 5, multiply 10 <br>
3. <input type="checkbox" value="3" multiply="5" class="sum"> value 3, multiply 5 <br>
<input type="hidden" value="0" id="sum">
value: <div id="view">
</div>
I want to know how to calculate the input values of the following fields
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
And update the span text and the hidden field value
TOTAL <span id="amountTotal">0 </span>
<input id="total" type="hidden" name="total" value="">
Thanks in advance
This should do what you want to achieve:
function displaySum () {
var sum = 0;
// iterate over the input fields
$('.auto-sum').each(function () {
var value = $(this).val() || 0;
var number = parseInt(value, 10); // parse the input value to an integer
if (isNaN(number)) {
number = 0;
}
sum += number; // add the value to the sum
});
// set the value of the two elements
$('#amountTotal').text(sum);
$('#total').val(sum);
}
// whenever the value of one of the input fields changes, call the displaySum function
$('.auto-sum').on('change, keyup', displaySum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
TOTAL <span id="amountTotal">0 </span>
<input id="total" type="hidden" name="total" value="">
I tried with blur method for after mouseleave from input and check all input values and added ! Then update to wanted element !!
$("input").on("blur",function(){
var total = 0;
$("[type='text']").each(function(){
if($(this).val() != "") {
total += parseInt($(this).val());
}
});
$("#amountTotal").text(total);
$("#total").val(total);
});
Try with query each() function .Use with parseFloat convert the string to number .for real time update do with keyup event
$('.auto-sum').keyup(function(){
var a=0;
$('.auto-sum').each(function(){
a+=parseFloat($(this).val())
})
$('#amountTotal').text(a|0)
$('#total').val(a|0)
console.log($('#total')[0].outerHTML)//its show the hidden field value
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum" value="2" >
<input type="text" name="score2" class="auto-sum" value="5">
<input type="text" name="score3" class="auto-sum" value="5">
TOTAL <span id="amountTotal" >0 </span>
<input id="total" type="hidden" name="total" value="">
You can use <input type="number" /> inputs to force values entered to be a number.
From there you can call jQuery with the query selector input.auto-sum to get all of the input elements with the class auto-sum
Using the each function you can add the numeric to an accumulator to get the total.
You can then use jQuery with the query selectors needed to set any other elements on the page with the Total value.
function getTotal() {
var total=0;
$('input.auto-sum').each(function(i,e)
{
total += Number($(e).val());
});
$('#amountTotal').text(total);
$('#total').val(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Score 1: <input type="number" name="score1" class="auto-sum"><br />
Score 2: <input type="number" name="score2" class="auto-sum"><br />
Score 3: <input type="number" name="score3" class="auto-sum"><br />
TOTAL: <span id="amountTotal">0 </span><br />
<input id="total" type="hidden" name="total" value="">
<input type="button" id="btnTotal" onclick="getTotal()" value="Get Total" />
Please try this one.
$('.auto-sum').on('change',function(){
var totalvalue=0;
$('.auto-sum').each(function(a,b){
totalvalue=totalvalue+parseInt(($(b).val()=='' || isNaN($(b).val()))?0:$(b).val());
});
$('#amountTotal').text(totalvalue);
$('#total').val(totalvalue);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
TOTAL <span id="amountTotal">0</span>
<input id="total" type="hidden" name="total" value="">
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
<input type="button" id="calculator" value="Caculate">
$("#calculator").on("click",function (){
var result=0;
var sum_fields=$(".auto-sum");
for(var i=0;i<sum_fields.length;i++){
if(!isNaN(sum_fields[i]) && sum_fields[i]>0){
result += sum_fields[i];
}
}
$("#amountTotal").text(result);
$("#total").val(result);
});
Create array for the fields and loop through them
Check if it not a NaN and more than 0 add them to the result then after the loop attach the result to the hidden field and as a span text
I post this as an answer because the comment areas are to small
At first i think it´s an good idea to write
<input type = "number">
when you don´t want to display the small arrows look at this solution:
https://css-tricks.com/snippets/css/turn-off-number-input-spinners/
the keyup event ist the best way to "live" display the total sum
At last take a look at vue.js
This is the best solution for this scenario.
if you're interested in a pure javascript solution:
All inputs have an oninput event attribute that fires when the input is changed.
You can attach an event handler to the event like so:
<input oninput="updateTotal" />
where updateTotal is a function declared in your script:
function updateTotal { /* code that updates the total */ }
OR if you select the input in your script then you can attach the event handler like this:
selectedInput.oninput = function updateTotal () {
...
}
Here's my implementation that selects all the inputs with the class "auto-sum", assigns the event handler to each of them and updates the code by looping over each input's value attribute:
https://jsfiddle.net/billy_reilly/5dd24v81/2/
function displaySum () {
var sum = 0;
// iterate over the input fields
$('.auto-sum').each(function () {
var value = $(this).val() || 0;
var number = parseInt(value, 10); // parse the input value to an integer
if (isNaN(number)) {
number = 0;
}
sum += number; // add the value to the sum
});
// set the value of the two elements
$('#amountTotal').text(sum);
$('#total').val(sum);
}
// whenever the value of one of the input fields changes, call the displaySum function
$('.auto-sum').on('change, keyup', displaySum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
TOTAL <span id="amountTotal">0 </span>
<input id="total" type="hidden" name="total" value="">
How can I get the value of the closest textbox and assign it into a variable? Then after getting the value, change the current value of that textbox by multiplying it by the value of previous textbox. I have three instances of divs with the same input elements so I think .closest() or .next() can help me. Here is a snippet of my code
HTML
<div class="box">
<b>1</b>
<input type="text" name="quantity" value="1"/>
<input type="checkbox" name="ignoreThisCheckbox" checked="checked"/>
<input type="text" name="price" value="10"/>
</div>
<div class="box">
<b>2</b>
<input type="text" name="quantity" value="1"/>
<input type="checkbox" name="ignoreThisCheckbox" checked="checked"/>
<input type="text" name="price" value="10"/>
</div>
<div class="box">
<b>3</b>
<input type="text" name="quantity" value="1"/>
<input type="checkbox" name="ignoreThisCheckbox" checked="checked"/>
<input type="text" name="price" value="10"/>
</div>
JS
$("input[name=quantity]").each(function(){
$(this).bind("change keyup", function(){
var q = $(this).val();
var p = parseFloat($(this).closest("input[name=price]").val()).toFixed(2);
var amount = q * p;
$(this).closest("input[name=price]").val(amount)
console.log(amount);
})
})
non working demo
http://jsfiddle.net/c6yfS/
Thank you for responses
/* NOTE */
The purpose of the checkbox is just to show that I have a checkbox in between the two elements concerned.
As mentioned by other posters, you can use .siblings as .closest searches up the DOM tree (i.e. parent elements). However there is also a logic error in your code as the price you retrieve is never the right per unit price if quantity is changed. You will need a separate unit price hidden value perhaps to facilitate this
Check out the updated code here: http://jsfiddle.net/c6yfS/1/
it's better to use data attribute in order to calculating correctly:
HTML:
<div class="box">
<b>1</b>
<input type="text" name="quantity" value="1"/>
<input type="checkbox" name="ignoreThisCheckbox" checked="checked"/>
<input type="text" name="price" data-value="10"/>
</div>
JS:
$('input[name=quantity]').on("change keyup", function(){
var q = 0;
var p = 0;
var amount = 0;
q = parseInt($(this).val(), 10);
p = parseInt($(this).siblings("input[name='price']").data('value'), 10);
amount = q * p;
if (amount) {
$(this).siblings("input[name='price']").val(amount)
console.log(amount);
} else {
$(this).siblings("input[name='price']").val('Please specify the quantity')
}
})
DEMO
.closest is used to find the closest element up the DOM tree. What you are looking for is siblings or next | prev.
http://api.jquery.com/siblings/
http://api.jquery.com/prev/
http://api.jquery.com/next/
So
$(this).siblings("input[name='price']").val(amount);
Edit
Here is the full working JS:
$("input[name=quantity]").each(function(){
$(this).bind("change keyup", function(){
var $thi,q,$p,p;
$thi = $(this);
q = $thi.val();
$p = $(this).siblings("input[name='price']");
p = parseFloat($p.val()).toFixed(2);
$p.val(q * p);
});
});
for clarity I've just add a total field
You can solve it with this code :
$("input[name=quantity], input[name=price]")
.each( function(){ $(this).on( {'keyup': function(){ var j0=$(this).nextAll("input[name=total]"); j0.val( j0.prevAll("input[name=quantity]").val() * j0.prevAll("input[name=price]").val() ) } } ) } );
Click here to see the working "Fiddle"