I am trying to use a simple function of javascript that was intended to be used with a SELECT dropdown with single digits, but now I need to use it for when visitors type in a value with decimal points. I am getting a NaN with the current javascript even when I type in 30 or any number. Any suggestions on how to get my total?
JAVASCRIPT:
$(function () {
$('.DoPricing').change(function () {
var total = 0;
$('.DoPricing').each(function () {
total += parseInt($(this).val());
});
$('#TotalPrice').html('$' + total);
});
});
HTML:
<form action="myactionpage.php" method="POST">
<table>
<tr>
<td>How much will you be paying today?</td>
<td>$<input type="text" name="howmuch" id="howmuch" placeholder="0.00" class="DoPricing"></td>
</tr>
<tr>
<td><div class="totalbox">Total Amount Due Today: <strong><span id="TotalPrice">$0.00</span></strong></div>
</td>
</tr>
<tr><td><input type="submit" id="submit" name="submit" value="Submit Payment" class="submitbut" /></td>
</tr>
</table>
</form>
Try this:
$(function () {
$('.DoPricing').on("keyup",function () {
var total = 0;
$('.DoPricing').each(function () {
total += parseFloat($(this).val()) || 0;
});
$('#TotalPrice').html('$' + total);
});
});
This accepts decimals now, here is the demo
Your basic example works for me. I'm guessing there are other elements on the page with class, but that don't necessarily have values, and that you'd like them to default to zero. When an input has no value, .val() returns the empty string, and parseInt('', 10) returns NaN, not 0, so you're not getting what you want.
This is very simple to fix:
total += parseInt($(this).val()) || 0;
Demo: http://jsfiddle.net/mattball/2rgku
I assume you want decimals as well but you're using parseInt instead of parseFloat and if you're using decimals (because it's money) then you should use toFixed. In the following code I assume the user will use the . as a decimal symbol and there should be only one . in the value (no thousands separator).
In your for each you convert a perfectly good usable this to a jQuery object only to get the value. I've changed $(this).val() to this.value so the conversion isn't needed.
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type="text/javascript" src="jquery-1.9.0.js"></script>
</head>
<body>
<form action="myactionpage.php" method="POST">
<table>
<tr>
<td>How much will you be paying this morning?</td>
<td>$<input type="text" name="howmuch" id="howmuch" placeholder="0.00" class="DoPricing"></td>
</tr>
<tr>
<td>How much will you be paying this evening?</td>
<td>$<input type="text" name="howmuch" id="howmuch1" placeholder="0.00" class="DoPricing"></td>
</tr>
<tr>
<td><div class="totalbox">Total Amount Due Today: <strong><span id="TotalPrice">$0.00</span></strong></div>
</td>
</tr>
<tr><td><input type="submit" id="submit" name="submit" value="Submit Payment" class="submitbut" /></td>
</tr>
</table>
</form>
<script type="text/javascript">
(function () {
function getValue(el) {
if (el.value === "") { return 0; }
var nr = parseFloat(el.value);
// only 0 to 9 or . and only one . used as decimal symbol
if (/[^0-9.]/.test(el.value) || /.*?\..*?\./.test(el.value)) {
return false;
}
return nr;
}
$('.DoPricing').on("keyup", null, null, function (e) {
var $this = $(this),
val = getValue(this),
total = 0;
if(val!==false){
$this.data("pref",val);
}else{
$this.val($this.data("pref")||"");
}
$('.DoPricing').each(function () {
total += parseFloat(this.value,10)||0;
});
$('#TotalPrice').html('$' + total.toFixed(2));
});
})();
</script>
</body>
</html>
Related
I'm trying to create comparison/validation of two numbers for retrieving the right number from the database.
I'm doing using PHP, HTML and retrieve the details of weight from XAMPP database to compare with user input.
I'm using type='number' so that user can only input digits.
HTML FORM
<form action="" method="POST" onSubmit= "return Validator_edit(this)">
<table class="midTable" align="center" cellpadding="3" cellspacing="3" enctype="multipart/form-data" >
<tr>
<tr>
<th align="right" >Weight:</th>
<td><input type="number" size="20" name="weight" id="weight" value="<?php echo $weight ?>" disabled="disabled"> * Weight that you have set previously <br/></td>
</tr>
<tr>
<th align="right" >Progress:</th>
<td><input type="number" name="progress" value="<?php echo $progress ?>" id="progress" >
* NOTE : Progress must NOT exceed the weight you have set .</strong><br></h3></td>
</tr>
<tr >
<td colspan='2' align='center'><input type="submit" value="update" name="submit" />
</tr>
</table>
</form>
Validation form
<script type="text/javascript" language="javascript">
function Validator_edit(frm){
if (frm.progress.value=="")
{
alert("progess must not be empty");
frm.progress.focus();
return false;
}
if (frm.progress.value > frm.weight.value )
{
alert(" You have exceed the weight.");
frm.progress.focus();
return false;
}
}
</script>
For some reason, it is able to validate "some" numbers. For example: I've set:
Weight = 50
logically progress under 50 will be able to be validated and return true.
However, it fails on 3, 4, 5, 6, 7, 8, 9, even though these numbers are less than 50.
How do I solve this problem?
Your numbers might be in string forms. You might try using a function such as Number(); in JavaScript and pass it through that, just to make sure, typeof your form progress values are number.
Maybe, try something similar to:
<script type="text/javascript" language="javascript">
function Validator_edit(frm){
if (frm.progress.value=="")
{
alert("progess must not be empty");
frm.progress.focus();
return false;
}
if (Number(frm.progress.value) > Number(frm.weight.value) )
{
alert(" You have exceed the weight.");
frm.progress.focus();
return false;
}
}
</script>
Or you might pass it through a regex, maybe similar to:
function is_number(form_progress_number) {
return /^\d+$/.test(form_progress_number);
}
This link might help you.
I have two field named "Input1" and "Input2" with id as "inputID".
If I click "Input1" field,Input2 field to be disable.
And after reset, If I click "Input2" field,Text" Input1 should be disable.
I can able to achieve this by different id in javascript. But I need to get this with same id.
Can anyone please me on this?
<!DOCTYPE html>
<html>
<body>
<script>
function myFunc1() {
var input1 = document.getElementById("input1");
var input2= document.getElementById("input2");
if (input1.click){
document.getElementById("input2").disabled=true;
}
}
function myFunc2() {
var input1 = document.getElementById("input1");
var input2= document.getElementById("input2");
if (input2.click) {
document.getElementById("input1").disabled=true;
}
}
</script>
<table>
<tr>
<td>Field1: <input type="text" id="input1" onclick="myFunc1();" /></td>
</tr>
<tr>
<td>Field2 : <input type="text" id="input1" onclick="myFunc2();" /></td>
</tr>
</table>
</body>
</html>
Like I said in my comment, the id's should be unique, but if you insist on doing this the way you have it planned now, just get the elements by name since they are unique.
function myFunc1() {
var input1 = document.getElementsByName("input1");
var input2= document.getElementsByName("input2");
if (input1.click){
input2.disabled=true;
}
}
The answer above works, however if you want to make it really dynamic and clean, I'd make a function like this:
$("input[type=text]").click(function() {
$("input[type=text]").not(this).attr("disabled", true);
});
$("button#reset").click(function() {
$("input[type=text]").attr("disabled", false);
});
This targets all input[type=text] except the one you clicked. Pretty simple and very little code.
DEMO http://jsbin.com/kegasehagi/edit?html,js,console,output
Here is a WORKING FIDDLE for you in pure Jquery.
$(function(){
$('input[type=text]').click(function(){
$('input[type=text]').each(function(){
if(!($(this).is(":focus"))){
$(this).attr('disabled',true);
}
});
});
});
But, I would suggest you to keep IDs different and use class instead.
I hope, It will solve your purpose.
you can add more inputs with class name inpu and it will works.
Pure JavaScript:
<!DOCTYPE html>
<html>
<head><title>test page</title></head>
<body>
<table>
<tr>
<td>Field1: <input type="text" class='inpu' onclick="focusonly(this);" /></td>
</tr>
<tr>
<td>Field2 : <input type="text" class='inpu' onclick="focusonly(this);" /></td>
</tr>
<tr>
<td>Field3 : <input type="text" class='inpu' onclick="focusonly(this);" /></td>
</tr>
<tr>
<td>Field4 : <input type="text" class='inpu' onclick="focusonly(this);" /></td>
</tr>
<tr>
<td><button onclick='reset();'>reset</button></td>
</tr>
</table>
<script>
function reset(){
var inpu = document.getElementsByClassName("inpu");
for(var i=0;i<inpu.length;i++){
document.getElementsByClassName("inpu")[i].value = "";
document.getElementsByClassName("inpu")[i].disabled = false;
}
}
function focusonly(el){
var inpu = document.getElementsByClassName("inpu");
for(var i=0;i<inpu.length;i++){
document.getElementsByClassName("inpu")[i].disabled = true;
}
el.disabled = false;
}
</script>
</body>
</html>
I'm working on creating a page in which someone could calculate their Net Worth by entering various values. The input text will show a .00 afterwards if no decimal point is added in. I'm having troubles in getting a sum of all of the values.
Java:
<script type="text/javascript"><!--
function updatesum() {
document.form.TotalAssets.value = (document.form.CashOnHand.value -0) + (document.form.CashInChecking.value -0);
}
//-->
</script>
HTML:
<input type="text" onblur="if(this.value.indexOf('.')==-1)this.value=this.value+'.00'" onchange="format(this); updatesum()" onkeyup="format(this)" maxlength="11" value="0" name="CashOnHand" /></td>
</tr>
<tr>
<td><strong>Cash in Checking</strong></td>
<td>$
<input type="text"
onblur="if(this.value.indexOf('.')==-1)this.value=this.value+'.00'" onchange="format(this); updatesum()" onkeyup="format(this)" maxlength="11" value="0" name="CashInChecking" /></td>
</tr>
<tr>
<td align="right"><strong>Total Assets</strong></td>
<td>$<input name="TotalAssets" readonly ></td>
</tr>
It's not giving me a sum of the the values that I'm adding.
I think this is because document.form is undefined, but this one works:
function updatesum() {
var hand = parseFloat(document.forms[0].CashOnHand.value);
var checking = parseFloat(document.forms[0].CashInChecking.value);
document.forms[0].TotalAssets.value = hand - checking;
}
help. I want to make something like this, for example, ill put a price on textboxAdd and when i press the button, textbox1 will copy the value of textboxAdd(where the 1st price is there). then I'll put again, (2nd price) on textboxAdd and press the button, the value of textboxAdd (which is the 2nd price), it will be in textbox2. pls Help. Thank You.
My code is here and the output:
<html>
<body>
<head>
<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<form>
<table>
<tr><td>Add to list:</td><td><input type="text" name="addkist" value=""> </td></tr>
<tr>
<td> </td>
<td align="center"><input type="button" value="ADD TO LIST"></td>
</form>
</tr>
<tr><td> </td><td> </td></tr>
<th align="center" colspan="2" bgcolor="0033CC"><font color="white">Shopping LIST</font></th>
<tr><td ><center>No.</center></td><td ><center>Amount</center></td></tr>
<tr><td ><center>01</td><td><input class="total" type=text name=01></td></tr>
<tr><td ><center>02</td><td><input class="total" type=text name=02></td></tr>
<tr><td ><center>03</td><td><input class="total" type=text name=03></td></tr>
<tr><td ><center>04</td><td><input class="total" type=text name=04></td></tr>
<tr><td ><center>05</td><td><input class="total" type=text name=05></td></tr>
<tr><td ><center>06</td><td><input class="total" type=text name=06></td></tr>
<tr><td ><center>07</td><td><input class="total" type=text name=07></td></tr>
<tr><td ><center>08</td><td><input class="total" type=text name=08></td></tr>
<tr><td >TOTAL:</td><td align="center"> <span id="sum">0</span></td></tr>
</td></table>
<script>
$(document).ready(function(){
$(".total").each(function()
{
$(this).keyup(function()
{
calculateSum();
});
});
});
function calculateSum()
{
var sum = 0;
//iterate through each textboxes and add the values
$(".total").each(function()
{
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0)
{
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
</script>
</body>
</html>
Here:
// First let's put an ID attribute to recognize your button:
<input type="button" id="btn-add-to-list" value="ADD TO LIST">
// Next, Change your script code to:
<script>
$(document).ready(function(){
num = 1; // this will be used to navigate to the next textbox
$("#btn-add-to-list").click(function(){
// get the current value of the textbox
val_to_add = $("input[name='addkist']").val();
// checking if number is entered
if(!isNaN(val_to_add) && val_to_add.length!=0)
{
// clear the textbox to add to
$("input[name='0"+num+"']").val('');
// add the value of 'addkist' textbox to 'textbox 01, 02, 03'
// etc.in sequence
$("input[name='0"+num+"']").val(val_to_add);
// increment counter to go the next texbox
num++;
// if the last textbox reached, reset the counter
if(num==9){num=1;}
calculateSum();
}
});
});
// this code of yours remains the way it was
function calculateSum()
{
var sum = 0;
//iterate through each textboxes and add the values
$(".total").each(function()
{
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0)
{
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
</script>
Fiddle Demo
Fiddle modified made as per the change in requirement mentioned in below comment:
Fiddle Demo allowing commas
I need to display the percentage each input value contains out of the full dataset.
So if the user inputs 3, 2 and 1. The "percent" inputfield should show "50, 30 and 20"
The thing is, i dont know how many inputs the form will get. It could be from 1 to any number.
The source html code is created by a partial view i created. The output is:
<table>
<tr>
<th>Name</th><th>Distributiob key</th><th>Percent</th>
</tr>
<tr>
<td>
House 1
</td>
<td>
<input type="text" size="5" value="0" id="LightPhysicalEntities_0__DistributionKey" name="LightPhysicalEntities[0].DistributionKey" />
</td>
<td>
<input type="text" size="5" id="LightPhysicalEntities_0__Percent" readonly=readonly />
</td>
</tr>
<tr>
<td>
House 2
</td>
<td>
<input type="text" size="5" value="0" id="LightPhysicalEntities_1__DistributionKey" name="LightPhysicalEntities[1].DistributionKey" />
</td>
<td>
<input type="text" size="5" id="LightPhysicalEntities_1__Percent" readonly=readonly />
</td>
</tr>
<tr>
<td>
House 3
</td>
<td>
<input type="text" size="5" value="0" id="LightPhysicalEntities_2__DistributionKey" name="LightPhysicalEntities[2].DistributionKey" />
</td>
<td>
<input type="text" size="5" id="LightPhysicalEntities_2__Percent" readonly=readonly />
</td>
</tr>
First field in the table is the title or name. Second is where the user punches in distribution number. Third is the readonly field with the calculated percentage.
The calculation should be done in javascript, but i cant quite crack the nut on how to get started, getting the inputs and setting the outputs.
A function like this should help (this will round down the percentages- replace the Math.floor if you want to handle differently):
function calcPcts() {
var distributions = $("[id$=DistributionKey]");
// Get the base first
var base = 0;
distributions.each(function () {
base += window.parseInt($(this).val(), 10);
});
// Now calculate the percentages of the individual ones
distributions.each(function () {
var input = $(this),
val = window.parseInt($(this).val(), 10),
pct = (val === 0) ? val : Math.floor((val / base) * 100);
$("#" + input.attr("id").replace("DistributionKey", "Percent")).val(pct);
});
}
If you add a class to the input fields you can use jQuery to get the number of items with that class. Then you can get the values and perform your calculations.
Here is an example:
var inputCount = $(".inputfield").length;
$("input[type='text']").change(function() {
var total = GetTotal();
for (i = 0; i < inputCount; i++) {
var inputValue = $('#LightPhysicalEntities_' + i + '__DistributionKey').val();
if (total != 0) {
var percent = inputValue / total;
$('#LightPhysicalEntities_' + i + '__Percent').val(percent);
}
}
});
function GetTotal() {
var total = 0;
for (i = 0; i < inputCount; i++) {
var inputValue = $('#LightPhysicalEntities_' + i + '__DistributionKey').val();
total += parseInt(inputValue);
}
return total;
}
Here is an example of the script working: http://jsfiddle.net/ZWuQr/