I need to solve some calculations and I'm using an .each() loop. I'm populating rows <tr> dynamically so I use .each() to loop through the table but I can't get different values when I have to sort them by vat value.
function callSum(id) {
var counter = 1;
var sum = document.getElementById("sum" + id).value;
var vat = document.getElementById("vat" + id).value;
$('.sumall').each(function() {
$('.vatall').each(function() {
if ($(this).val() == 0) { //if value of VAT is 0 sum it to vatTotalZero
document.getElementById("vatTotalZero").value = $(this, ".sumall").val; // don't know how to solve this
} else { //if value of VAT is > 0 sum it to vatTotal
document.getElementById("vatTotal").value = $(this, ".sumall").val; // don't know how to solve this
}
counter++;
});
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<tr>
<td class="col-sm-1">
<input type="text" name="sum[]" id="sum1" onfocus="callSum(1)" class="sumall form-control"/>
</td>
<td class="col-sm-1">
<input type="text" name="vat[]" id="vat1" class="vatall form-control "/>
</td>
</tr>
<br><br>
<label>All Sums without VAT (vat 0)</label>
<input type="text" name="vatTotalZero" id="vatTotalZero" class="form-control "/>
<br><br>
<label>All Sums with VAT (vat > 0)</label>
<input type="text" name="vatTotal" id="vatTotal" class="form-control "/>
Please see disrciptive comments in the source code.
function callSum(id) {
var counter = 1,
sum = document.getElementById("sum" + id).value,
vat = document.getElementById("vat" + id).value,
sumallVal;
$('.sumall').each(function () {
/* get the value */
sumallVal = $(this).val();
$('.vatall').each(function () {
if ($(this).val() == 0) { //if value of VAT is 0 sum it to vatTotalZero
//document.getElementById("vatTotalZero").value = $(this, ".sumall").val; // don't know how to solve this
/* set the value */
$("#vatTotalZero").val( sumallVal )
} else { //if value of VAT is > 0 sum it to vatTotal
//document.getElementById("vatTotal").value = $(this, ".sumall").val; // don't know how to solve this
/* set the value */
$("#vatTotal").val( sumallVal )
}
counter++;
});
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<tr>
<td class="col-sm-1">
<!-- <input type="text" name="sum[]" id="sum1" onfocus="callSum(1)" class="sumall form-control" /> -->
<input type="text" name="sum[]" id="sum1" onchange="callSum(1)" class="sumall form-control" />
</td>
<td class="col-sm-1">
<input type="text" name="vat[]" id="vat1" class="vatall form-control " />
</td>
</tr>
<br>
<br>
<label>All Sums without VAT (vat 0)</label>
<input type="text" name="vatTotalZero" id="vatTotalZero" class="form-control " />
<br>
<br>
<label>All Sums with VAT (vat > 0)</label>
<input type="text" name="vatTotal" id="vatTotal" class="form-control " />
Here we go with an enhanced version.
In this version I removed unused stuff, set an appropriate event handler and shortened the syntax slightly
function callSum(id) {
var sum = document.getElementById("sum" + id).value,
vat = document.getElementById("vat" + id).value,
sumallVal;
$('.sumall').each(function () {
/* get the value */
sumallVal = $(this).val();
$('.vatall').each(function () {
/* set the value */
$( $(this).val() == 0 ? "#vatTotalZero" : "#vatTotal" ).val( sumallVal )
});
});
}
$(document).ready(function() {
$('.sumall.form-control').on('input', function() {
// get number id directly from string id by deleting all non numbers
callSum( this.id.replace(/[^0-9]/gi, '') );
})
});
<tr>
<td class="col-sm-1">
<!-- <input type="text" name="sum[]" id="sum1" onfocus="callSum(1)" class="sumall form-control" /> -->
<input type="text" name="sum[]" id="sum1" class="sumall form-control" />
</td>
<td class="col-sm-1">
<input type="text" name="vat[]" id="vat1" class="vatall form-control " />
</td>
</tr>
<br>
<br>
<label>All Sums without VAT (vat 0)</label>
<input type="text" name="vatTotalZero" id="vatTotalZero" class="form-control " />
<br>
<br>
<label>All Sums with VAT (vat > 0)</label>
<input type="text" name="vatTotal" id="vatTotal" class="form-control " />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Related
I am using javascript calculation. multiply 2 numbers: number 1 * number 2 = total and how g-total but working only one value display?
I have need number 1 * number 2 = total and show Gtotal so please help and share a valuable idea...
HTML
<input
name="per_hour"
id="per_hour"
class="form-control"
value=""
onblur="perhour()"
placeholder="0"
/>
<input
name="per_hour_x"
id="per_hour_x"
class="form-control"
onblur="perhour()"
value=""
placeholder="0.00"
/>
Total
<input
name="per_hour_total"
id="per_hour_total"
class="form-control"
value=""
placeholder="0.00"
/>
G-Total
<input
type="text"
class="form-control total-fare"
id="total"
disabled
value="<?= $booking->total_fare ?>"
/>
<script>
function perhour() {
var per_hour = document.getElementById("per_hour").value;
var per_hour_x = document.getElementById("per_hour_x").value;
var amts = document.getElementById("total").value;
var totaperhour = Number(per_hour) * Number(per_hour_x);
var totalamt = Number(totaperhour) + Number(amts);
$("#per_hour_total").val(totaperhour).toFixed(2); //working
$("#total").val(totalamt).toFixed(2); //not working
}
</script>
It should be $('#per_hour_total').val(totaperhour.toFixed(2)); and not $('#per_hour_total').val(totaperhour).toFixed(2);
function perhour() {
var per_hour = document.getElementById("per_hour").value;
var per_hour_x = document.getElementById("per_hour_x").value;
var amts = document.getElementById("total").value;
var totaperhour = Number(per_hour) * Number(per_hour_x);
var totalamt = Number(totaperhour) + Number(amts);
$('#per_hour_total').val(totaperhour.toFixed(2));
$('#total').val(totalamt.toFixed(2));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div>
total
<input type="text" class="form-control total-fare" disabled id="total" value="">
</div>
<div>
per_hour
<input name="per_hour" id="per_hour" class="form-control" value="" onblur="perhour()" placeholder="0">
</div>
<div>
per_hour_x
<input name="per_hour_x" id="per_hour_x" class="form-control" onblur="perhour()" value="" placeholder="0.00">
</div>
<div>
per_hour_total
<input name="per_hour_total" id="per_hour_total" class="form-control" value="" placeholder="0.00">
</div>
I am using Codeignator, I am calculating the final amount. If any user enters the total amount that will calculate it and display in the final amount field.
I am adding the input field dynamically as well. I tried some code but it's not working.
I need to calculate using AJAX.
What I am trying to achieve is, This is my first page.
Now if any user enters the total amount something like this then it will display in the final amount field.
If the user wants to add more field the should click on add button and add the price and it will calculate it and display in the field box, I added in the 50.
same as on this.
Would you help me out in this?
$(document).ready(function() {
var max_fields = 20; //maximum input boxes allowed
var wrapper = $(".row_set"); //Fields wrapper
var add_button = $(".add_row_click"); //Add button ID
var baseUrl = "http://localhost/test/";
var x = 1; //initlal text box count
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div class="row_set custom_fields"><input type="text" name="single_price[]" id="single_p_price' + x + '" placeholder="single price"> <input type="text" name="total_p_price[]" id="total_p_price' + x + '" placeholder="total amount"><div class="btn_row remove_field"> <span> - </span> Remove </div></div>');
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
//$(this).parent('custom_fields').remove();
$(this).closest('.custom_fields').remove();
x--;
})
/*comment start here $(".medication_info").on('keyup', 'input[id^=total_p_price]', function() {
var that = $(this); // CHANGE HERE
var total_p_price = that.val();
$.ajax({
type: "POST",
url: baseUrl + "/Access_control/calculate_amt",
data: {
total_p_price: total_p_price
},
cache: false,
success: function(html) {
console.log(html);
var single_price = $('#final_amt').val(html);
}
});
});comment end here*/
$('.medication_info').on('keyup', 'input[id^=total_p_price]', function() {
var totalSum = 0;
$('input[id^=total_p_price]').each(function() {
var inputVal = $(this).val();
if ($.isNumeric(inputVal)) {
totalSum += parseFloat(inputVal);
}
});
$('#final_amt').val(totalSum);
});
});
<form>
<div class="medication_info">
<div class="row_set">
<input type="text" name="single_price[]" id="single_p_price" placeholder="single price">
<input type="text" name="total_p_price[]" id="total_p_price" placeholder="total amount">
</div>
<div class="btn_row add_row_click"> <span> + </span> Add </div>
<input type="text" name="final_amt" id="final_amt" placeholder="Final total">
</div>
<input type="submit" name="send" value="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Controller
public function calculate_amt()
{
$total_p_price=$this->input->post('total_p_price');
foreach ($total_p_price as $key => $value) {
$final_amt +=$value;
}
echo $final_amt;
}
Both jQuery and using AJAX to involve a server seems overkill for this operation.
//Find elements in HTML
var singleProductPriceInput = document.getElementById("single_p_price");
var totalProductAmountInput = document.getElementById("total_p_price");
var finalTotalInput = document.getElementById("final_amt");
var button = document.getElementById("submitter");
//Update function
function updatePrice() {
var singleProductPrice = parseFloat(singleProductPriceInput.value);
var totalProductAmount = parseFloat(totalProductAmountInput.value);
var result = (singleProductPrice * totalProductAmount);
if (!isNaN(result)) {
finalTotalInput.value = result.toFixed(2);
}
}
//Submit function
function submit() {
alert("Do your server stuff\nAJAX here");
}
//Bind event listeners
singleProductPriceInput.addEventListener("change", updatePrice);
singleProductPriceInput.addEventListener("keyup", updatePrice);
singleProductPriceInput.addEventListener("mouseup", updatePrice);
totalProductAmountInput.addEventListener("change", updatePrice);
totalProductAmountInput.addEventListener("keyup", updatePrice);
totalProductAmountInput.addEventListener("mouseup", updatePrice);
button.addEventListener("click", submit);
<form>
<div class="medication_info">
<div class="row_set">
<input type="number" name="single_price[]" id="single_p_price" placeholder="single price">
<input type="number" name="total_p_price[]" id="total_p_price" placeholder="total amount">
</div>
<div class="btn_row add_row_click"> <span> + </span> Add </div>
<input type="text" name="final_amt" id="final_amt" placeholder="Final total" readonly>
</div>
<input id="submitter" type="button" name="send" value="submit">
</form>
simple Javascript KeyUp Event calculation
$("input").keyup(function () {
var pr = $(this).data("price");
var name = $(this).data("name");
var qut = $(this).val();
var total = pr * qut;
$("#"+name).text(total);
});
$("#placeorder").click(function () {
var total = 0;
$('.t').each(function () {
total += Number($(this).text());
});
$('#total').text(total);
});
.t{
border:0px solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Bone Burger:</td>
<td><input type="text" data-name="gold" data-price="28" size="1" /></td>
<td> * 28r.s<td>
<td>= <label id="gold" class="t" readonly ></label>r.s</td>
</tr>
<tr>
<td>Smoke Burger:</td>
<td><input type="text" data-name="sakti" data-price="29" size="1" /></td>
<td> * 29r.s<td>
<td>= <label id="sakti" class="t" readonly ></label>r.s</td>
</tr>
<tr>
<td>Voodoo Burger:</td>
<td><input type="text" data-name="taja" data-price="30" size="1" /></td>
<td> * 30r.s<td>
<td>= <label id="taja" class="t" readonly ></label>r.s</td>
</tr>
<tr>
<td>Ayhuaska Sour:</td>
<td><input type="text" data-name="gay" data-price="18" size="1" /></td>
<td> * 18r.s<td>
<td>= <label id="gay" class="t" readonly ></label>r.s</td>
</tr>
<tr>
<td>Beyond the Pale:</td>
<td><input type="text" data-name="chhash" data-price="10" size="1" /></td>
<td> * 10r.s<td>
<td>= <label id="chhash" class="t" readonly ></label>r.s</td>
</tr>
<tr>
<td>
<button id="placeorder">Place order</button>
</td>
</tr>
<tr>
<td><p>Total:<span id="total"></span></p></td>
</tr>
</table>
This might be what you want
$(document).ready(function() {
var max_fields = 20; //maximum input boxes allowed
var wrapper = $(".row_set"); //Fields wrapper
var add_button = $(".add_row_click"); //Add button ID
var baseUrl = "http://localhost/test/";
var x = 1; //initlal text box count
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div class="row_set custom_fields"><input type="text" name="single_price[]" id="single_p_price' + x + '" placeholder="single price"> <input type="text" name="total_p_price[]" class="total_p_price" id="total_p_price' + x + '" placeholder="total amount"><div class="btn_row remove_field"> <span> - </span> Remove </div></div>');
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
//$(this).parent('custom_fields').remove();
$(this).closest('.custom_fields').remove();
x--;
})
$(".medication_info").on('keyup', 'input[id^=total_p_price]', function() {
// Sum all the values in the total_p_price fields
var that = $(this);
$.ajax({
type: "POST",
url: baseUrl + "/Access_control/calculate_amt",
data: {
total_p_price: $(".medication_info .total_p_price").serialize()
},
cache: false,
success: function(html) {
console.log(html);
var single_price = $('#final_amt').val(html);
}
});
});
});
<form>
<div class="medication_info">
<div class="row_set">
<input type="text" name="single_price[]" id="single_p_price" placeholder="single price">
<input type="text" name="total_p_price[]" class="total_p_price" id="total_p_price" placeholder="total amount">
</div>
<div class="btn_row add_row_click"> <span> + </span> Add </div>
<input type="text" name="final_amt" id="final_amt" placeholder="Final total">
</div>
<input type="submit" name="send" value="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I'm trying to make a validation condition for the field Total. Total project costs is invalid: The maximum sum for Total project costs is 9,999,999,999,999.99. Once it is more than this value, the border of the text and the text would be red. Would appreciate any help.
<tr style="height:35px">
<td> </td>
<td align="center"><strong>TOTAL</strong></td>
<td align="center">
<input class="numeral form-control text-font-md" disabled="disabled" style="width:auto; height:30px" value="" type="text" data-bind="attr: {'title': totalRequestfromNEHToolTip}, value: tRequestfromNEH">
</td>
<td align="center">
<input class="numeral form-control text-font-md" disabled="disabled" style="width:auto; height:30px" disabled="" type="text" data-bind="attr: {'title': totalRequestfromNEHToolTip}, value: tnonFedThirdPartyGifts">
</td>
</td>
<td align="center">
<input class="numeral form-control text-font-md" disabled="disabled" style="width:auto; height:30px" value="" type="text" data-bind=" attr: {'title': totalCostShareToolTip}, value: tcostShare">
</td>
<!-- <td align="center"><input class="numeral form-control text-font-md" disabled="disabled" style="width:auto; height:30px" value="" type="text"></td> -->
var TOTAL = ko.computed(function() {
var total = 0;
var hasUserInput = false;
if (tRequestfromNEH() != '' && tRequestfromNEH() != undefined) {
hasUserInput = true;
total = total + Number(String(tRequestfromNEH()).replace(/\,/g, ''));
}
if (tnonFedThirdPartyGifts() != '' && tnonFedThirdPartyGifts() != undefined) {
hasUserInput = true;
total = total + Number(String(tnonFedThirdPartyGifts()).replace(/\,/g, ''));
}
if (tcostShare() != '' && tcostShare() != undefined) {
hasUserInput = true;
total = total + Number(String(tcostShare()).replace(/\,/g, ''));
}
if (total == 0) {
if (!hasUserInput)
return '';
else
return formatNumber('0');
} else {
if (loading == false) {
sendCommand('SAVE');
}
return formatNumber(total);
}
});
use the knockout css binding. here is one where the text and background go red when the total exceeds 10. https://jsfiddle.net/0o89pmju/57/
html
<form>
<div class="form-group">
<label for="number1">number 1</label>
<input type="number" class="form-control" id="number1" data-bind="textInput: number1">
</div>
<div class="form-group">
<label for="number1">number 2</label>
<input type="number" class="form-control" id="number2" data-bind="textInput: number2">
</div>
<div class="form-group" data-bind="css: {'has-error': total() > 10 }">
<label class="control-label">Total:</label>
<p class="form-control-static" data-bind="text: total, css: {'bg-danger': total() > 10 }"></p>
</div>
</form>
js
function viewModel() {
var self = this;
this.number1 = ko.observable('');
this.number2 = ko.observable('');
this.total = ko.pureComputed(function(){
return parseInt(self.number1()||0) + parseInt(self.number2()||0)
},this);
}
var vm = new viewModel();
(function($) {
ko.applyBindings(vm); //bind the knockout model
})(jQuery);
First of all, sorry for my bad english language.
So, I want to sums my 2 coloumn, but i have add.row condition.
Here my code :
<script>
$(function(){
$('.qty, .unit').on('blur', function(e){
var qty = parseFloat( $('.qty').val() ),
unit = parseFloat( $('.unit').val() );
if( isNaN(qty) || isNaN(unit) ) {
$('.result').text('');
return false;
}
var total = qty * unit;
$('.result').text( total );
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td><input type="text" class="form-control qty" name="p_qty[]" /></td>
<td><input type="text" class="form-control unit" name="p_harga[]" /></td>
<td><strong><span class="result" name="p_jumlah[]"></span></strong></td>
here my screenshoot
Screenshoot
when im run, this code success but only in row 1 and not work in row 2++
how can i fix it?
Thank you so much.
Try this
<script src="../js/plugins/jquery.js"></script>
<script>
$(function () {
$('.form-control').blur(function () {
var qty = $('.qty').val();
var total = 0;
$('.unit').each(function () {
total += parseInt(this.value);
});
// Update the total
$('.result').text(qty * total);
});
});
</script>
<input type="text" class="form-control qty" name="p_qty[]" />
<input type="text" class="form-control unit" name="p_harga[]" />
<!-- Two or more fields -->
<input type="text" class="form-control unit" name="p_harga[]" />
<input type="text" class="form-control unit" name="p_harga[]" />
<strong><span class="result" name="p_jumlah[]"></span></strong>
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);
}
});
});
});