Here's a script, that will add all the Float values entered in input fields. But I am getting a problem at ROUNDING THE VALUE. With my script, Value before decimal point is rounding off after 0.99(like Price of an item). but I want to round off the value after 0.59(like minutes).
When the Calculate button is clicked, the value will be displayed in another input field.
function add_number() {
var first = parseFloat(document.getElementById("sunday").value);
var second = parseFloat(document.getElementById("monday").value);
var third = parseFloat(document.getElementById("tuesday").value);
var forth = parseFloat(document.getElementById("wednesday").value);
var fifth = parseFloat(document.getElementById("thursday").value);
var sixth = parseFloat(document.getElementById("friday").value);
var seventh = parseFloat(document.getElementById("saturday").value);
var rsl = first + second + third + forth + fifth + sixth + seventh;
document.getElementById("txtresult").value = rsl.toFixed(2);
}
<input type="number" name="sunhrs" id="sunday" />
<input type="number" name="monhrs" id="monday" />
<input type="number" name="tuesday" id="tuesday" />
<input type="number" name="wedhrs" id="wednesday" />
<input type="number" name="thurshrs" id="thursday" />
<input type="number" name="frihrs" id="friday" />
<input type="number" name="sathrs" id="saturday" />
<button onclick="add_number()">Calculate</button>
<br>
<br>
<input type="number" name="txtresult" id="txtresult" />
Example: If I entered 1.50,1.50 in input fields and click on calculate button the output will be 3.00 as the value is rounded off after 0.99. but i want the value rounded after 0.59 So, that the output will be 3.40.
Thanks in advance.
EDITED: The first problem in the post (it was befaore I change); the word "result" is special for JavaScript and I have not use it for a variable name.
Secondly, forgot to add element which has an id is txtresult
;) thx your attention.
In order to add these values together the way you want, you'll need to convert your inputs to fractional hours, and then convert back from fractional hours to the desired representation. JavaScript does not have an "hours" data structure built in. The JavaScript Number type has a decimal base, so it can only work like regular decimal numbers.
e.g.
var first = hoursFromString(document.getElementById("sunday").value);
//etc.
then
document.getElementById("txtresult").value = stringFromHours(result);
If you need help writing hoursFromString or stringFromHours, please update your question with more information on the part you're having trouble with.
Related
Something that has bugged me for a while and always giving me headaches.
I have an input field with a value in numbers
<input id="base-life" class="base-stats" type="number" name="base-life" value="20" readonly />
I am picking up the value of the input field with
let charlife = document.getElementById('base-life');
I have a number with which i want to increase the value of the base-life input field. This of course changes dynamically based on other stuff but let's say it's 2
let increaseWith = 2;
in an onclick function i want to increase base-life with 2 (base-life + 2) everything it is clicked
function increase() {
charlife.value += increaseWith;
}
Now this only adds 2 to the value of the input field, makes it 202. I know that this happens when one of the numbers are actually strings. Perhaps my charlife. I tried everything and it gets worse. I tried parseInt(charlife.value) - no luck. I tried other methods but it doesn't work. And i only have this problem with input fields. When the element is just a or another simpler html element - it all works easier. Has to do with how JS parses input fields. Can someone shed some light?
let charlife = document.getElementById('base-life');
let increaseWith = 2;
function increase() {
value = parseInt(charlife.value);
value += increaseWith;
charlife.value = value;
}
<input id="base-life" class="base-stats" type="number" name="base-life" value="20" readonly />
<button onclick="increase()">Increase</button>
Here is the working snippet with some custom code that is according to your specifications
<input id="base-life" class="base-stats" type="number" name="base-life" value="20" readonly />
<button class="add" onclick="let increaseWith = 2;document.getElementById('base-life').value = parseInt(document.getElementById('base-life').value)+increaseWith;">add</button>
The HTML looks like this:
<div>
<label class="sr-only" for="product">Product</label>
<input id="product" type="text" placeholder="Product" maxlength="7" autofocus>
<label class="sr-only" for="batch">Batch</label>
<input id="batch" type="text" placeholder="Batch" maxlength="5">
</div>
The jQuery looks like this:
$('#product').on('keyup', function() {
let product = $(this).val().slice(0, 7);
let batch = $(this).val().slice(9, 14);
if ($(this).val() && $(this).val().length === 7) {
$(this).val(product);
$(this).next().focus().val(batch);
}
});
When I'm scanning the barcode, it reads this string WXYZ519 -8012456789.
I need to slice this string so that the input with id="product" and id="batch" gets the values as WXYZ519 and 80124 respectively without the hyphen and space in between.
The first input does receive the right value but I just couldn't get the second input to slice the right value into it.
Can anyone tell me why and what's wrong with my code?
Your range appears to be wrong if you wanted to get the entire 2nd half of the string.
If you change
$(this).val().slice(9, 14);
to
$(this).val().slice(9, $(this).val().length);
it will contain a string that starts at 9 and ends at the end of the string.
Another alternative which I believe is much cleaner and less error prone would be this:
let split = $(this).val().split(" -");
let product = split[0];
let batch = split[1];
I have a normal input as follows:
<input type="number" name="quantity" id="myInput">
If I type "1." (without the quotes of course) when I try to get the value of the input with
document.getElementById("myInput").value
Only an empty string is obtained.
Is there any other way to get the "1." input with javascript?
Edit
I am working using Polymer 1.0 and databinding, so in my example I showed using normal JavaScript syntax with the intention of finding a solution to my problem using only javascript.
I just want to know how to access a property that returns the value of the input, and which I believe should be stored in some property of the object.
If you use <input type="number"> the element is enriched with an extra attribute, valueAsNumber. So instead of
document.getElementById("myInput").value
use
document.getElementById("myInput").valueAsNumber
valueAsNumber will return NaN instead of blank if the value entered in the input not is convertable to a number. There is also a validity attribute holding information of the status of the current value, both according to the value as supposed number but also according to the number input's settings, i.e "why is the number invalid".
Fun with number inputs, try this out in various browsers :
<input type="number" name="quantity" id="myInput" ><br>
<input type="text" id="value" ><br>
<input type="text" id="valueAsNumber" ><br>
<input type="text" id="validity" ><br>
document.getElementById("myInput").onkeyup = function() {
document.getElementById("value").value = this.value;
document.getElementById("valueAsNumber").value = this.valueAsNumber;
document.getElementById("validity").value = '';
for (validity in this.validity) {
if (this.validity[validity]) {
document.getElementById("validity").value+=validity+' ';
}
}
}
actually quite informative, if you want to investigate exactly why you get an empty value back from the input -> http://jsfiddle.net/oaewv2Lr/ Have tried with Chrome, Opera and FF - Chrome seems to be the most "forgiving" browser of those three.
I found a way to get invalid values:
Focus the input.
Select its contents using execCommand().
Grab the selection using window.getSelection().
Example:
document.querySelector('input[type="submit"]').addEventListener('click', function() {
var inp= document.getElementById('myInput');
inp.focus();
document.execCommand('SelectAll');
var value = window.getSelection().toString();
document.getElementById('output').textContent = value;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" name="quantity" id="myInput">
<input type="submit">
<div id="output"></div>
It won't work if you will enter 1., as 1. is not a valid number.
Update: It seems that your use of type="number" means that certain values won't come back. You can switch it to a type="text" and do the checking yourself:
document.getElementById('mySubmit').addEventListener('click', function() {
var value = document.getElementById('myInput').value;
if ( value != parseFloat(value) )
alert('Invalid Number');
document.getElementById('myOutput').innerHTML = value;
});
<input type="text" name="quantity" id="myInput">
<input type="submit" id="mySubmit">
<div id="myOutput"></div>
Before you says its duplicate, I am not asking how to actually format the price. But asking where I am doing it wrong or what else I should do to implement it the way I want.
I did the price formatting ( actually by copying the code from somewhere )
http://jsfiddle.net/qwY24/
like for price 1
but now I want to format the price in the input field itself (price 2), it work fine till 6 digit but then after that it get messed up. It got two problem
Format messed up after 6 digit
when press back key(delete number) the price doesn't reformat after 6 digit only
Code
$(".price1").on("keyup",function(){
var price = $(this).val();
$(".formatted1").text(price.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"));
});
$(".price2").on("keyup",function(){
var price = $(this).val();
price = price.replace(",","");
$(".price2").val(price.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"));
$(".formatted2").text(price.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"));
});
<label>Price 1</label>
<input type="text" class="price1" /><br />
<label><b>Price 1 Formatted:</b></label>
<span class="formatted1"></span><br /><br /><br />
<label>Price 2</label>
<input type="text" class="price2" /><br />
<label><b>Price 2 Formatted</b></label>
<span class="formatted2" ></span><br /><br /><br />
price.replace(",","") replaces only the first instance of comma, not all of them. Replace it with
price = price.replace(/,/g,"");
(Also, the .toString() part in the next line is unnecessary because the variable is already a string.)
Demo: http://jsfiddle.net/qwY24/3/
I have built a table with custom inputs numbers with jeditable. The Input type is gone once you put the value
I need to find a JavaScript Real Time Calculation which automatically makes the amount of my values.
I have found 2 interesting examples very suitable for my case but there is the possibility to achieve it the same without using the form and inputs?
First example
Second example
Yes, it is. As you know a div element can be accessed by document.getElementById('div_id') and its value can be accessed by document.getElementById('div_id').value.
So take out the form and insert an id for the div's that you need and access the value and then find the sum and then set the value as the sum to another div. Here is the code
<script>
function calculateBMI() {
var wtStr =document.getElementById('w').value;
if (!wtStr)
wtStr = '0';
var htStr = document.getElementById('h').value;
if (!htStr)
htStr = '0';
var weight = parseFloat(wtStr);
var height = parseFloat(htStr);
document.getElementById("r").value = weight + height;
}
</script>
<input id = "w" type="Text" name="weight" size="4" onkeyup="calculateBMI()"> Weight (in Kilos)
<input id = "h" type="Text" name="height" size="4" onkeyup="calculateBMI()"> Height (in Centimeters)<br>
<input id = "r" type="Text" name="BodyMassIndex" id="BodyMassIndex" size="4"> BMI
<input type="button" style="font-size: 8pt" value="Calculate" onClick="calculateBMI()" name="button">
and if you don't want input you can use textarea.