Javascript multiple update the same field - javascript

FIDDLE: http://jsfiddle.net/hReB3/6/
Javascript code:
$('#qty').keyup(function(){
if($(this).val() != '' && isNumber($(this).val()) && $(this).val() > 0)
{
var price = $('#real_price').val() * 1;
var qty = $(this).val() * 1;
var total = price * qty;
$('#price').html(total);
}
else
{
$('#price').html('500');
}
});
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
If I'm updating the price for the first field, it works fine, but for the second doesnt.
I'm new into javascript :).

JSFiddle
Using classes on your fields instead of IDs (IDs must be unique) and enclosing them within a parent DIV would allow you to use this code and gives you scope to add as many sections to your page as you need.
HTML
<div>
Price $<span class="price">500</span>
<input type="hidden" class="real_price" value="500" />
<input type="text" class="qty" value="1" />
</div>
<div>
Price $<span class="price">500</span>
<input type="hidden" class="real_price" value="500" />
<input type="text" class="qty" value="1" />
</div>
JS
$('.qty').keyup(function () {
var $me = $(this),
$parent = $me.parent('div'),
total = 500;
if (isNumber($me.val()) && $me.val() > 0)
{
var price = $parent.find('.real_price').val() * 1,
qty = $me.val() * 1;
total = price * qty;
}
$parent.find('.price').html(total);
});
You could also replace your hidden fields with data-price attributes as shown here JSFiddle

Can you try this, You can't able to use id value in more elements, instead that you can use classname etc, I have updated your fiddle code,
HTML:
Price $<span id="price_qty_1">500</span>
<input type="hidden" id="real_price_qty_1" value="500" />
<input type="text" id="qty_1" class="qty" value="1"/><br />
Price $<span id="price_qty_2">500</span>
<input type="hidden" id="real_price_qty_2" value="500" />
<input type="text" id="qty_2" class="qty" value="1"/>
Jquery:
$('.qty').keyup(function(){
if($(this).val() != '' && isNumber($(this).val()) && $(this).val() > 0)
{
var idAt = $(this).attr('id');
var price = $('#real_price_'+idAt).val() * 1;
var qty = $(this).val() * 1;
var total = price * qty;
$('#price_'+idAt).html(total);
}
else
{
$('#price_'+idAt).html('500');
}
});
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Demo : http://jsfiddle.net/hReB3/10/

Try this
<input type="text" id="qty1" value="1"/><br />
<input type="text" id="qty2" value="1"/>
$('#qty1,#qty2').keyup(function(){})
And in the price evaluation time replace this with
$('#price').html(total);
with
($(this).attr('id')=="qty1") ? $('#price1').html(total) : $('#price2').html(total);

Related

Change prices based on checkbox click

im currently looking for help in this matter.
The problem here is that instead of doing the checkbox value + the previous value it is adding it all together like placing "10" and after other checkbox click it adds the value to it and does not count it like "1020" instead of doing 10+20
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var total = 0;
$("input[type=checkbox]:checked").each(
function() {
total = total + parseInt($(this).val());
});
var input = document.getElementById("valor");
input.value += input.value + total;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Comissões Técnicas</label>
<label class="container newlabel">CPT
<input type="checkbox" value="10" name="cpt" >
<span class="checkmark"></span>
</label><br>
<label class="container newlabel">CPGA (Gratuito para Sócios da SPG)
<input type="checkbox" value="10" name="cpga" >
<span class="checkmark"></span>
</label><br>
<input id="valor" type="text">
Check if repeatedly click on checkbox should be handled also on uncheck score should reduced.
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var total = 0;
total = parseInt(document.getElementById("valor").value);
if(isNaN(total)){
total = 0;
}
if($(this).prop('checked')){
total = total + parseInt($(this).val());
} else {
total = total - parseInt($(this).val());
};
var input = document.getElementById("valor");
input.value = total;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Comissões Técnicas</label>
<label class="container newlabel">CPT
<input type="checkbox" value="10" name="cpt" >
<span class="checkmark"></span>
</label><br>
<label class="container newlabel">CPGA (Gratuito para Sócios da SPG)
<input type="checkbox" value="20" name="cpga" >
<span class="checkmark"></span>
</label><br>
<input id="valor" type="text">
The code
input.value += input.value + total;
means (since input.value is a String), concatenate input.value with total after making sure total is a String. Don't use the += and be sure to use parseInt() on anything that you want to be a number.
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var total = 0;
$("input[type=checkbox]:checked").each(
function() {
total = total + parseInt($(this).val());
});
var input = document.getElementById("valor");
/*
* You don't need +=
* You do need to parseInt
* You need to make sure to handle empty String ""
*/
input.value = (parseInt(input.value, 10) || 0) + total;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Comissões Técnicas</label>
<label class="container newlabel">CPT
<input type="checkbox" value="10" name="cpt" >
<span class="checkmark"></span>
</label>
<br>
<label class="container newlabel">CPGA (Gratuito para Sócios da SPG)
<input type="checkbox" value="10" name="cpga" >
<span class="checkmark"></span>
</label><br>
<input id="valor" type="text">
Please correct me, if I don't quite understand your problem, but shouldn't you just have to change input.value += input.value + total; to input.value = total; for the required result?
As you are using jQuery and I love to user reduce method I can advice you this solution
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var total = $('input[type=checkbox]:checked').toArray().reduce(function(pre, post) {
return pre + parseInt($(post).val());
}, 0);
$('#valor').val(total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Comissões Técnicas</label>
<label class="container newlabel">CPT
<input type="checkbox" value="10" name="cpt" >
<span class="checkmark"></span>
</label><br>
<label class="container newlabel">CPGA (Gratuito para Sócios da SPG)
<input type="checkbox" value="20" name="cpga" >
<span class="checkmark"></span>
</label><br>
<input id="valor" type="text">
If your value is always a number you can use value / 1 to convert number string into numeric type. This only if you are SURE that the number will be always a number and not a string containing number, eg. 11.jpg is not valid.
This is a performance test for your case:
https://jsperf.com/parseint-versus-divide-by-one/1
So you can rewrite the code as:
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var total =
$('input[type=checkbox]:checked').toArray().reduce(function(pre, post) {
var val = $(post).val() / 1;
return pre + (val ? val : 0);
}, 0);
$('#valor').val(total);
});
});

Calculate the values of input where each input has different prices. Any shorter code for this?(javascript only)

The code below is working fine but what if there are 100 inputs? any shorter way to do this?
function checkTotal() {
var a = document.getElementById("sandwich").value;
var b = document.getElementById("burger").value;
var c = document.getElementById("cake").value;
var d = document.getElementById("coffee").value;
document.getElementById("total").value = parseInt(a) * 10 + parseInt(b) * 5 + parseInt(c) * 15 + parseInt(d) * 20;
}
<form role="form" name="listForm">
<label>Sandwich</label>
<input type="number" id="sandwich" value="0" onkeyup="checkTotal()"><br>
<label>Burger</label>
<input type="number" id="burger" value="0" onkeyup="checkTotal()"><br>
<label>Cake</label>
<input type="number" id="cake" value="0" onkeyup="checkTotal()"><br>
<label>Coffee</label>
<input type="number" id="coffee" value="0" onkeyup="checkTotal()"><br> Total: <input type="text" size="2" name="total" id="total" value="0" />
</form>
1) Here each input article has a different price.
2) The value of the input should be mutiply with its price given(Eg. if the sandwich has a price:30, and user inputs value 2 it should calculte the total=price*input value.)
3) i have my code which is working fine but is the above code is the right way to do?
4) what if there are 100 of article inputs. is there shorter code or should i create variable for each one?
what if there are 100 of article inputs. is there shorter code or
should i create variable for each one?
You can maintain a map
var idPriceMap = {
"sandwich" : 20,
"burger" : 10,
"cake" : 5,
"coffee" : 10
};
You can iterate this and produce your value using reduce
var output = Object.keys( idPriceMap ).reduce( function(a,b){
var value = +document.getElementById( b ).value;
a += value * idPriceMap[ b ];
return a;
}, 0);
document.getElementById( "total" ).value = output;
Another way to try is to give your elements a class and some data attributes that can be retrieved by JavaScript using dataset. You can then use them to make your calculations. That way you get rid of ids and you just have to change the HTML code to add a new element.
function checkTotal() {
var total = 0,
foods = document.querySelectorAll('.food');
for (var i = 0; i < foods.length; i++) {
var food = foods[i],
name = food.dataset.item,
price = parseInt(food.dataset.price),
howMany = parseInt(food.value);
console.log(howMany, name, 'costs', (howMany * price));
total += howMany * price;
}
document.getElementById('total').value = total;
}
<form role="form" name="listForm">
<label>Sandwich</label>
<input class="food" data-item="sandwich" data-price="30" type="number" value="0" onBlur="checkTotal()"><br>
<label>Burger</label>
<input class="food" data-item="burger" data-price="10" type="number" value="0" onBlur="checkTotal()"><br>
<label>Cake</label>
<input class="food" data-item="cake" data-price="5" type="number" value="0" onBlur="checkTotal()"><br>
<label>Coffee</label>
<input class="food" data-item="coffee" data-price="15" type="number" value="0" onBlur="checkTotal()"><br>
Total: <input type="text" size="2" name="total" id="total" value="0" />
</form>
As a side note, you should give a try on Angular or Knockout which can help you to achieve those operations.

How to calculate the total value of each section separately: Jquery

I have more than 10 section that included three inputs in each section as follows:
<div class="product_quantity">
<div class="color-quantity">
<input onkeydown="return myFunction(event);" name="custom_small" class="custom_small" type="text">
<input onkeydown="return myFunction(event);" name="custom_medium" class="custom_medium" type="text">
<input onkeydown="return myFunction(event);" name="custom_large" class="custom_large" type="text">
</div>
<div class="color-quantity">
<input onkeydown="return myFunction(event);" name="white_small" class="custom_small" type="text">
<input onkeydown="return myFunction(event);" name="white_medium" class="custom_medium" type="text">
<input onkeydown="return myFunction(event);" name="white_large" class="custom_large" type="text">
</div>
</div>
I am calculating the product quantity from each section but its giving me the whole amount of products on the basis of amount entered in every input. but i want the amount of products in section separately
I am using jQuery to do so please check the code and recommend the changes as required:
jQuery(".color-quantity input").each(function () {
if (this.value) {
quantity += (this.value) * 1;
classname = jQuery(this).attr('class');
arr.push(classname);
}
if (quantity == '') {
quantity = 0;
}
});
You can get total off each section as an array like following.
var arr = $('.color-quantity').map(function () {
var total = 0;
$('input', this).each(function () {
total += this.value * 1;
});
//do some stuff
if (total < 50) {
$('.btn-cart').removeAttr("onclick");
}
return total;
}).get();
console.log(arr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="color-quantity">
<input type="text" value="1">
<input type="text" value="2">
<input type="text" value="3">
</div>
<div class="color-quantity">
<input type="text" value="4">
<input type="text" value="5">
<input type="text" value="6">
</div>
You might try a nested loop. first loop through the color-quantity divs, then through the inputs. like this:
jQuery(".color-quantity").each(function () {
var quantity = 0;
$(this).find('input').each(function() {
if (this.value) {
quantity += (this.value) * 1;
classname = jQuery(this).attr('class');
arr.push(classname);
}
if (quantity == '') {
quantity = 0;
}
});
// here is where you can get the total value for each div
});

jQuery iterate through input fields and disable

I have a question I'm trying to figure out...
I have a lot of inputs in a form, but I only need to iterate through the ones in the div with player class.
<div class="player">
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
</div>
What I need is to iterate through them all once an input field has been modified and calculate how many of the input fields have 0 in them and if its 1 or more than 4 disable submit button.
I've been trying like this but it doesn't seem to work
$(document).ready(function()
{
$(function()
{
var $sum = parseInt($("#sum").text(), 10);
var $num = 0;
if(($sum == 0))
{
$("button[name=submit2]").attr("disabled", "disabled");
}
$(".player input[type=text]").bind("DOMSubtreeModified", function()
{
$.each($("input[type=text]"),function(){
if (!isNaN(+this.value))
{
++$num;
}
});
if (($num > 4) || ($num == 1))
$("button[name=submit2]").attr("disabled", "disabled");
else
$("button[name=submit2]").removeAttr("disabled");
});
})
});
I've also tried
$(document).ready(function(){
$(".unit").each(function() {
$(this).keyup(function(){
CheckNull();
});
});
function CheckNull() {
var $num = 0;
$(".unit").each(function() {
if(!isNaN(this.value) && this.value.length!=0) {
++$num;
}
});
if (($num > 4) || ($num == 1))
$("button[name=submit2]").attr("disabled", "disabled");
else
$("button[name=submit2]").removeAttr("disabled");
}
});
Try changing
if(!isNaN(this.value) && this.value.length!=0) {
++$num;
}
with
if($(this).val() != "" && $(this).val() !=0) {
++$num;
}
to be more jQuery style
I guess this is what you want :
// control function
function checkInputs() {
var num = 0;
// foreach inputs
$(".player input").each(function(i,item) {
var value = $(this).val();
if (value.trim() === "0") {
num++;
}
});
if (num === 1 || num > 4) {
$("#myForm input[type='submit']").attr("disabled", "true");
} else {
$("#myForm input[type='submit']").removeAttr("disabled");
}
}
// if you want a first check after loading the page :
checkInputs();
$(".player input").change(
// This function will be called each time an input change in the player div
checkInputs
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="myForm">
<div class="player">
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
</div>
<input type="submit"/>
</form>
I am not sure why are you checking the length? this.value.length!=0
I tweaked your code, here is the fiddle link : http://jsfiddle.net/bLa6evpg/
Hope this help!
I couldn't follow your function, but I believe your problem is that you are running it on page load, and not on the onchange of your input boxes. I achieved the desired functionality by doing that in this codepen
html:
<div class="player">
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number"/>
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
</div>
<button name="submit2">Click</button>
JS:
function validateChanges() {
var playerDiv = document.getElementsByClassName("player")[0];
var inputs = playerDiv.getElementsByTagName("input");
var total = 0;
for(var i = 0; i < inputs.length; i++) {
total += parseInt(inputs[i].value);
}
if(total == 1 || total > 4) { // IF total is 1 or more then 4
document.getElementsByTagName("button")[0].disabled = true;
} else {
document.getElementsByTagName("button")[0].disabled = false;
}
}
looks like i was almost right just messed up a bit Silent_coder fixed this +i added some tricks i saw here
$(document).ready(function(){
CheckNull();
$(".player input").each(function() {
$(this).keyup(function(){
CheckNull();
});
});
function CheckNull() {
var $num = 0;
$(".player input").each(function() {
if(this.value != 0 ) {
$num++;
}
});
if (($num > 4) || ($num <= 1))
$("button[name=submit2]").attr("disabled", "disabled");
else
$("button[name=submit2]").removeAttr("disabled");
}
});
Works like i charm for me ^^
Here is a JsFiddle example
$(function () {
$('.unit').on('change', function () {
var units = 0;
$('.unit').each(function (index, value) {
var unit = parseInt($(value).val(),10);
units += unit;
if(units >= 4 || units === 1) {
$('form > button').prop('disabled', true);
} else {
$('form > button').prop('disabled', false);
}
});
});
});

Get value from element id instead of name in javascript

I have some line of javascript which is works well if it gets value from the same series of names. But I have a problem later when each values passed to another page which I'd like to break down which value is belongs to. So the question is how can I change the way the script calculate the value from 'name' to 'id'. As the codes below:
<script type="text/javascript">
//auto commas
function doThousands(n) {
n = '' + n;
if (n.length < 4) return n;
var c = n.length % 3;
var pre = n.substring(0, c);
return pre + (pre.length? ',' : '') + n.substring(c).match(/\d{3}/g).join(',');
}
//sub total
function checkTotal() {
document.cc_form.total.value = '';
var sum = <?=$days*$_rate*$_rooms?>;
for (i=0;i<document.cc_form.cost.length;i++) {
if (document.cc_form.cost[i].checked) {
sum = sum + parseInt(document.cc_form.cost[i].value);
}
}document.cc_form.total.value = doThousands(sum);
}
</script>
And this is the HTML:
<form name="cc_form" id="cc_form" method="post" action="/">
<label for="transfer1"><input type="checkbox" id="transfer1" name="cost" value="800" autocomplete="off" onchange="checkTotal()" /> Taxi (800 THB | 2 pax)</label><br />
<label for="transfer2"><input type="checkbox" id="transfer2" name="cost" value="1200" autocomplete="off" onchange="checkTotal()" /> Mini Van (1,200 THB | 6 pax)</label><br />
<label for="xbed"><input type="checkbox" id="xbed" name="cost" value="1200" autocomplete="off" onchange="checkTotal()" /> Extra Bed (1,200 THB)</label><br />
<input type="text" id="total" name="total" />
</form>
document.getElementById http://www.w3schools.com/jsref/met_doc_getelementbyid.asp

Categories