How to validate total sum through jquery? - javascript

I have this field where the total amount is written and another field below the total amount field which can be appended multiple times by jQuery and the total amount written in field below can't exceed the amount in the total amount field. Is there any way to calculate this?
Form:
<div class="form-group">
<label>Total Cost</label>
<input type="number" name="total_cost" id="total_cost" class="form-control">
</div>
<div class="col-md-6">
<label>Amount</label>
<div class="input-group">
<input type="text" name="scheduled[1][amount]" class="form-control txt-schedule-amount" placeholder="Enter Amount">
</div>
</div>

As addition to Optimus answer you can add these lines:
$('body').on('keyup','.txt-schedule-amount',function(){
if(!calculateSum()) return false;
return true;
})
Which will check amounts during editing

I think you are looking for this.
function calcSum(obj){
var tAmmount =0;
$( ".txt-schedule-amount" ).each(function() {
tAmmount = tAmmount + valueParse($(this).val());
});
var costVal = valueParse($('#total_cost').val());
if(tAmmount > costVal){
alert('Your ammount exceed.');
if(obj==false)
$(".txt-schedule-amount").val(0);
else
$(obj).val(0);
}
}
function valueParse(svalue){
svalue = parseFloat(svalue);
if(isNaN(svalue))
svalue = 0;
return svalue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label>Total Cost</label>
<input type="number" name="total_cost" id="total_cost" class="form-control" onblur="calcSum(false)">
</div>
<div class="col-md-6">
<label>Amount</label>
<div class="input-group">
<input type="text" name="scheduled[1][amount][]" class="form-control txt-schedule-amount" onblur="calcSum(this)" placeholder="Enter Amount">
<input type="text" name="scheduled[1][amount][]" class="form-control txt-schedule-amount" onblur="calcSum(this)" placeholder="Enter Amount">
</div>
</div>

I think this is what you need.On submit call this function
function calculateSum(){
var sum =0;
$( ".txt-schedule-amount" ).each(function() {
sum = sum + parseInt($(this).val());
});
$("#total_cost").val(sum);
}

Related

JQuery returns NaN value while calculating multiple inputs in a row

I have a multiple input rows and all rows have a total column at the end. Now, I want to put the total result of each rows in column Total. I tried but it returns NaN value instead of total result. Attached is my view & script please help what I am missing??? Thanks
$('body').on('change', '.bgpending, .registered', function() {
var el = $(this);
var totalRow = 0;
el.closest('.dosiaPlace').find('input').each(function() {
totalRow = totalRow + parseInt($(this).val());
});
el.closest('.dosiaPlace').find('.total-row').val(totalRow);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dosiaPlace">
<div class="col-md-2">
<label>#lang('dashboard.pastyear'):</label>
<input type="number" value="0" class="form-control bgpending" name="bgpending[]" />
</div>
<div class="col-md-2">
<label>#lang('dashboard.warida'):</label>
<input type="number" value="0" class="form-control registered" name="registered[]" />
</div>
<div class="col-md-2">
<label>#lang('dashboard.total'):</label>
<input type="text" class="form-control total-row" />
</div>
</div>
Result:
The container, the .dosiaPlace, I presume, has 3 inputs: the .bgpending, the .registered, and the .total-row. Your el.closest('.dosiaPlace').find('input') finds all 3 of those, including the .total-row. But the .total-row is empty (initially), so
totalRow = totalRow + parseInt($(this).val());
for it results in
totalRow = totalRow + parseInt('');
And the empty string can't be parseInt'd (results in NaN). (You also probably don't want to be including the .total-row anyway)
Use input:not(.total-row') instead of input:
$('body').on('change', '.bgpending, .registered', function() {
var el = $(this);
var totalRow = 0;
el.closest('body').find('input:not(.total-row)').each(function() {
totalRow = totalRow + parseInt($(this).val());
});
el.closest('body').find('.total-row').val(totalRow);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-2">
<label>#lang('dashboard.pastyear'):</label>
<input type="number" value="0" class="form-control bgpending" name="bgpending[]" />
</div>
<div class="col-md-2">
<label>#lang('dashboard.warida'):</label>
<input type="number" value="0" class="form-control registered" name="registered[]" />
</div>
<div class="col-md-2">
<label>#lang('dashboard.total'):</label>
<input type="text" class="form-control total-row" />
</div>
Your variable get null value or NaN just asign o if it is nan or empty
if(totalRow=='' || totalRow ==NaN )
{
totalRow=0;
}

how to send the html form value in js page to use in another function

I'm trying to send the value of GST to order.js file if and only if the value of VAT mode is selected to be "with Vat" form the page new_order.php
<div class="form-group row">
<label for="vat" class="col-sm-3 col-form-label" onChange="getVatMode(this.value);" align="right">VAT Mode</label>
<div class="col-sm-6">
<select name="vatMode" value="data" class="form-control" id="vatMode" required="required">
<option value="1">Without VAT</option>
<option value="2">With VAT</option>
</select>
</div>
</div>
<div class="form-group row">
<label for="gst" class="col-sm-3 col-form-label" align="right">GST (13%)</label>
<div class="col-sm-6">
<input type="text" readonly name="gst" class="form-control form-control-sm" id="gst" required/>
</div>
</div>
and I need to pass this value of VAT to be passed to order.js page without loading for calculation of sum
function calculate(dis,paid){
var sub_total = 0;
var gst = 0;
var net_total = 0;
var discount = dis;
var paid_amt = paid;
var due = 0;
$(".amt").each(function(){
sub_total = sub_total + ($(this).html() * 1);
})
gst = Math.round(0.13 * sub_total);
net_total = gst + sub_total;
net_total = net_total - discount;
due = net_total - paid_amt;
$("#gst").val(gst);
$("#sub_total").val(sub_total);
$("#discount").val(discount);
$("#net_total").val(net_total);
//$("#paid")
$("#due").val(due);
With Jquery you can use $("#YourFormId").serialize():
$("form").on( "submit", function( event ) {
event.preventDefault();
console.log($(this).serialize());
});
For a form element's value to be included in the serialized string, the element must have a name attribute
https://api.jquery.com/serialize/

Javascript percentage calculation for each form field

I'm trying to work out the percentage value for each field in a form. However my current code is only working out the value for the first field or whichever one is focused.
I'd like it so that the percentage value only for the filed in the same fieldset
The current code works but i'd like to apply to to multiple fieldsets without them interfering with other inputs on the same page
In the snippet you can see that the two separate amounts which are editing each others details
function percentageCal() {
var $price = $(".form-item--invamt .form-item__input").on("input", calculatePerc),
$percentage = $(".form-item__input-expand .percentage").on("input", calculatePrice),
$currency = $(".form-item__input-expand .currency").on("focus", removePercent),
$none = $(".form-item--charges .no-charge").on("focus", removePercent),
$increase = $(".wrapper-types__percentage-value"),
$increaseWrap = $(".wrapper-types__percentage");
$($percentage).add($currency).keypress(function(event) {
if (event.which != 8 && event.which != 0 && (event.which < 48 || event.which > 57)) {
return false;
}
});
function calculatePrice() {
var percentage = parseFloat($(this).val());
var price = parseFloat($price.val());
var calcPrice = parseFloat((price * percentage / 100).toFixed(2));
var newPrice = price + calcPrice;
$increase.text(newPrice);
$increaseWrap.fadeIn();
if (isNaN(newPrice)) {
$increaseWrap.hide();
}
}
function calculatePerc() {
var percentage = $percentage.val();
var price = parseFloat($(this).val());
var calcPerc = parseFloat((price * percentage / 100).toFixed(2));
var newPrice = price + calcPerc;
$increase.text(newPrice);
}
function removePercent() {
$increaseWrap.fadeOut();
}
}
percentageCal();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset class="wrapper-types__investment">
<legend class="sr-only">Investment 1</legend>
<div class="form-item form-item--required form-item--invamt">
<label class="form-item__label" for="wrappers[0]">Investment amount</label>
<div class="form-item__input-labelled">
<span class="form-item__input-label">£</span>
<input class="form-item__input " type="number" name="wrappers[0]" id="wrappers[0]" min="0" value="15000" required>
</div>
</div>
<div class="form-item form-item--charges-wrap">
<span class="form-item__label">Charges</span>
<div class="form-item form-item--charges">
<label class="form-item__input-label-expand" for="percentage1">%</label>
<div class="form-item__input-expand">
<input class="form-item__input percentage" type="number" name="percentage" id="percentage1">
</div>
</div>
</div>
<div class="form-item form-item--charges-wrap">
<span class="wrapper-types__percentage">= £<span class="wrapper-types__percentage-value"></span></span>
</div>
<div class="form-item form-item--action-btns">
</div>
</fieldset>
<fieldset class="wrapper-types__investment">
<legend class="sr-only">Investment 2</legend>
<div class="form-item form-item--required form-item--invamt">
<label class="form-item__label" for="wrappers[1]">Investment amount</label>
<div class="form-item__input-labelled">
<span class="form-item__input-label">£</span>
<input class="form-item__input " type="number" name="wrappers[1]" id="wrappers[1]" min="0" value="13005.02" required>
</div>
</div>
<div class="form-item form-item--charges-wrap">
<span class="form-item__label">Charges</span>
<div class="form-item form-item--charges">
<label class="form-item__input-label-expand" for="percentage2">%</label>
<div class="form-item__input-expand">
<input class="form-item__input percentage" type="number" name="percentage" id="percentage2">
</div>
</div>
</div>
<div class="form-item form-item--charges-wrap">
<span class="wrapper-types__percentage">= £<span class="wrapper-types__percentage-value"></span></span>
</div>
<div class="form-item form-item--action-btns">
</div>
</fieldset>
Instead of IDs, use classes and DOM traversal functions to find the fields in the same fieldset.
function percentageCal() {
var $price = $(".form-item--invamt .form-item__input").on("input", calculatePerc),
$percentage = $(".form-item__input-expand .percentage").on("input", calculatePrice),
$currency = $(".form-item__input-expand .currency").on("focus", removePercent),
$none = $(".form-item--charges .no-charge").on("focus", removePercent),
$increase = $(".wrapper-types__percentage-value"),
$increaseWrap = $(".wrapper-types__percentage");
$percentage.add($currency).keypress(function(event) {
if (event.which != 8 && event.which != 0 && (event.which < 48 || event.which > 57)) {
return false;
}
});
function calculatePrice() {
var $fieldset = $(this).closest("fieldset");
var percentage = parseFloat($(this).val());
var price = parseFloat($fieldset.find(".form-item--invamt .form-item__input").val());
var calcPrice = parseFloat((price * percentage / 100).toFixed(2));
var newPrice = price + calcPrice;
$fieldset.find(".wrapper-types__percentage-value").text(newPrice);
$fieldset.find(".wrapper-types__percentage").fadeIn();
if (isNaN(newPrice)) {
$fieldset.find(".wrapper-types__percentage").hide();
}
}
function calculatePerc() {
var $fieldset = $(this).closest("fieldset");
var percentage = $fieldset.find(".form-item__input-expand .percentage").val();
var price = parseFloat($(this).val());
var calcPerc = parseFloat((price * percentage / 100).toFixed(2));
var newPrice = price + calcPerc;
$fieldset.find(".wrapper-types__percentage-value").text(newPrice);
}
function removePercent() {
var $fieldset = $(this).closest("fieldset");
$fieldset.find(".wrapper-types__percentage").fadeOut();
}
}
percentageCal();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset class="wrapper-types__investment">
<div class="form-item--invamt">
<div>
<span class="form-item__input-label">£</span>
<input class="form-item__input " type="number" name="wrappers[0]" id="wrappers[0]" min="0" value="15000" required>
</div>
</div>
<div class="form-item--charges-wrap">
<div class="form-item--charges">
<label class="form-item__input-label-expand" for="percentage">%</label>
<div class="form-item__input-expand">
<input class="form-item__input percentage" type="number" name="percentage" id="percentage">
</div>
</div>
</div>
<div class="form-item--charges-wrap">
<span class="wrapper-types__percentage">= £<span class="wrapper-types__percentage-value"></span></span>
</div>
</fieldset>
<fieldset class="wrapper-types__investment">
<div class="form-item--invamt">
<div>
<span class="form-item__input-label">£</span>
<input class="form-item__input " type="number" name="wrappers[1]" id="wrappers[1]" min="0" value="15000" required>
</div>
</div>
<div class="form-item--charges-wrap">
<div class="form-item--charges">
<label class="form-item__input-label-expand" for="percentage1">%</label>
<div class="form-item__input-expand">
<input class="form-item__input percentage" type="number" name="percentage" id="percentage1">
</div>
</div>
</div>
<div class="form-item--charges-wrap">
<span class="wrapper-types__percentage">= £<span class="wrapper-types__percentage-value"></span></span>
</div>
</fieldset>

How to get sum of input values?

hello im trying to add input totals to a grand total when any input is changed. i keep getting NaN in the total box. here is my code
<div class="col-md-6">
<input type="text" placeholder="Description" class="form-control" id="d" name="description" />
</div>
<div class="col-md-1">
<input type="text" placeholder="price." class="form-control" id="q" name="itemprice"/>
</div>
<div class="col-md-1">
<input type="text" placeholder="price" class="form-control" id="itemprice" name="itemprice1"/>
</div>
<div class="col-md-2">
<input type="text" placeholder="price" class="form-control" id="itemprice" name="itemprice2" onchange="myFunction()"/>
<td>Subtotal</td>
<td class="total" id="tot" for="tot">
<input type="total" id="total">
<script type="text/javascript">
function myFunction()
{
var answer = document.getElementById('total');
var x = document.getElementsByName('itemprice');
var y = document.getElementsByName('itemprice1');
var z = document.getElementsByName('itemprice2');
var d = document.getElementsByName('itemprice3');
answer.value = x.value + y.value + z.value + d.value;
}
</script>
Use Id's (fix duplicate id, remove reference to itemprice3 as it doesn't exist in the HTML). Convert text values to numbers before adding.
<div class="col-md-6">
<input type="text" placeholder="Description" class="form-control" id="d" name="description" />
</div>
<div class="col-md-1">
<input type="text" placeholder="price." class="form-control" id="itemprice" name="itemprice"/>
</div>
<div class="col-md-1">
<input type="text" placeholder="price" class="form-control" id="itemprice1" name="itemprice1"/>
</div>
<div class="col-md-2">
<input type="text" placeholder="price" class="form-control" id="itemprice2" name="itemprice2" onchange="myFunction()"/>
<td>Subtotal</td>
<td class="total" id="tot" for="tot">
<input type="total" id="total">
<script type="text/javascript">
function myFunction()
{
var answer = document.getElementById('total');
var x = document.getElementById('itemprice');
var y = document.getElementById('itemprice1');
var z = document.getElementById('itemprice2');
//var d = document.getElementsById('itemprice3');
// parseFloat converts to values, otherwise you'll concatenate the strings.
answer.value = parseFloat( "0" + x.value ) + parseFloat("0" + y.value) + parseFloat("0" + z.value); // + d.value;
document.getElementsByName returns a nodelist (because multiple nodes can have the same name). (That's why the name contains Elements with an 's' as opposed to getElementById, which returns 1 element at most.
Such a list doesn't have a value. You would either get the value of each element, or if you know it will always be one, get the value of the first element:
var y = document.getElementsByName('itemprice1')[0].value
But note, you don't have any elements that have the name itemprice3, so document.getElementsByName('itemprice3') will return a nodelist with 0 items. The line above will fail in that case.
Also note, you have two elements with id itemprice, which is illegal.
When that works, you will need parseInt() to convert the values to integers.
answer.value = parseInt(x.value) + parseInt(y.value) + parseInt(z.value) + parseInt(d.value);
If the inputs can contain floating point values as well, use parseFloat instead of parseInt.
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

How to subtract two text box values and display in another text box using Javascript

I want to fins the range between two number entered in a textbox and display it in another text box.
I am using the event onBlur.
Initially i got NaN in the result textbox.
Later I used ParseInt now no value is getting displayed.
My code :
<script type="text/javascript">
function countRows(){
var rows=document.getElementById("rows");
var startMsisdn=parseInt(document.getElementByName("startmsisdn").value);
var endMsisdn=parseInt(document.getElementByName("endmsisdn").value);
rows.value=endMsisdn-startMsisdn;
}
</script>
HTML CODE :
<div class="col-md-4">
<label>MSISDN Start Range </label> <input class="form-control"
type="text" name="startmsisdn"
placeholder="MSISDN Starting Range" required>
</div>
<div class="col-md-4">
<label>MSISDN End Range </label> <input class="form-control"
type="text" name="endmsisdn" placeholder="MSISDN Ending Range"
required>
</div>
</div>
<br>
<div class="row">
<div class="col-md-4">
<label>IMSI Start Range </label> <input class="form-control"
type="text" name="startimsi" placeholder="IMSI Starting Range"
required>
</div>
<div class="col-md-4">
<label>IMSI End Range </label> <input class="form-control"
type="text" name="endimsi" placeholder="IMSI Ending Range"
required onblur="countRows()">
</div>
<div class="col-md-4">
<label>No of rows </label> <input class="form-control"
type="text" name="rows" id="rows"
required>
</div>
Add default value for empty field
Try to get element by id for input field;
like this
Html
div class="col-md-4">
<label>IMSI Start Range </label>
<input class="form-control"
type="text" id="startimsi" name="startimsi" placeholder="IMSI Starting Range"
required>
</div>
<div class="col-md-4">
<label>IMSI End Range </label>
<input class="form-control"
type="text" id="endimsi" name="endimsi" placeholder="IMSI Ending Range"
required onblur="countRows()">
</div>
Javascript
var startMsisdn=parseInt(document.getElementById("startmsisdn").value) || 0;
var endMsisdn=parseInt(document.getElementById("endmsisdn").value) || 0;
You have two issues here. parseInt may return NaN, so any value you add to it will also always return NaN. The second issue is there is no getElementByName method (singular). It's getElementsByName which returns an array-like object:
function countRows(){
var rows=document.getElementById("rows");
var startMsisdn=parseInt(document.getElementsByName("startmsisdn")[0].value, 10) || 0;
var endMsisdn=parseInt(document.getElementsByName("endmsisdn")[0].value, 10) || 0;
rows.value=endMsisdn-startMsisdn;
}
You may notice that I added an extra parameter to your parseInt too. This is to force non-ES5 compliant browsers to parse as decimal - they may default to using octal for parsing which will result in unexpected results if a zero-prefixed value is entered.
Working Example
function countRows(){
var rows=document.getElementById("rows");
var startMsisdn=parseInt(document.getElementsByName("startmsisdn")[0].value, 10) || 0;
var endMsisdn=parseInt(document.getElementsByName("endmsisdn")[0].value, 10) || 0;
rows.value=endMsisdn-startMsisdn;
}
<div class="col-md-4">
<label>MSISDN Start Range </label>
<input class="form-control" type="text" name="startmsisdn" placeholder="MSISDN Starting Range" required>
</div>
<div class="col-md-4">
<label>MSISDN End Range </label>
<input class="form-control" type="text" name="endmsisdn" placeholder="MSISDN Ending Range" required>
</div>
<br>
<div class="row">
<div class="col-md-4">
<label>IMSI Start Range </label>
<input class="form-control" type="text" name="startimsi" placeholder="IMSI Starting Range" required>
</div>
<div class="col-md-4">
<label>IMSI End Range </label>
<input class="form-control" type="text" name="endimsi" placeholder="IMSI Ending Range" required onblur="countRows()">
</div>
<div class="col-md-4">
<label>No of rows </label>
<input class="form-control" type="text" name="rows" id="rows" required>
</div>
</div>
try this by replacing NaN with 0 ..
function countRows(){
var rows = document.getElementById("rows");
var startMsisdn=document.getElementById("startmsisdn").value;
if(startMsisdn =='' ){ startMsisdn =0;}
var endMsisdn=document.getElementById("endmsisdn").value;
if(endMsisdn =='' ){ endMsisdn =0;}
rows.value= parseInt(endMsisdn) - parseInt(startMsisdn);
}
HERE is the FIDDLE
Add These line of code in script its will work fine.
function countRows() {
var rows = document.getElementById("rows");
var startMsisdn = parseInt(document.getElementsByName("startmsisdn")[0].value);
var endMsisdn = parseInt(document.getElementsByName("endmsisdn")[0].value);
rows.value = endMsisdn - startMsisdn;
}

Categories

Resources