I have 2 HTML textboxes and need to convert them to numbers so I can perform a calculation but I am just getting NaaN. My code is:
Where totalcost is html textbox
and pg is also a html textbox
document.getElementById("totalcost").value = parseFloat(document.getElementById("pg").value) + parseFloat(document.getElementById("totalcost").value);
I want the totalcost box to be populated by "totalcost + pg" as it is a click and add cart system. Why Float, its for bitcoin.
Try this:
// get the `pg` value and attempt to convert to a Number, otherwise default to 0.00
var pg = Number(document.getElementById("pg").value) || 0.00;
// get the `totalcost` value and attempt to convert to a Number, otherwise default to 0.00
var totalCost = Number(document.getElementById("totalcost").value) || 0.00;
// update the `totalcost` element to include the sum of `pg` and `totalcost`
document.getElementById("totalcost").value = pg + totalCost
Added some comments to help explain each step.
Lets do that:
function isNumeric(n) {
/* http://stackoverflow.com/a/1830844/603774 */
return !isNaN(parseFloat(n)) && isFinite(n);
}
function calc() {
var
d_1 = document.getElementById('d_1').value,
d_2 = document.getElementById('d_2').value,
result;
/* Validation for d_1 */
if (!isNumeric(d_1)) {
alert('d_1 is not a number');
return;
}
/* Validation for d_2 */
if (!isNumeric(d_2)) {
alert('d_2 is not a number');
return;
}
result = +d_1 + +d_2;
alert('Result: ' + result);
}
<input type="text" id="d_1"> + <input type="text" id="d_2"> <input type="button" value="calculate" onclick='calc()'>
Use the unary plus operator with or conditional
document.getElementById("totalcost").value = (+(document.getElementById("pg").value) || 0) + (+(document.getElementById("totalcost").value) || 0);
Related
I want to replace a number over 100 with commas. Like 1000 to 1,000 and 1000000 to 1,000,000 etc. in HTML. I have found the code on here to do so but it only works with predetermined numbers being passed. I don't want it to work for a predetermined number but for any number typed into the box.
<label for="turnover">Estimated Monthly Card Turnover:</label><br />
<span>£ </span><input type="text" id="turnover" maxlength="11"
name="turnover" size="10" required>*
<br /><br />
<script type="text/javascript">
$('#turnover').keydown(function(){
var str = $(this).val();
str = str.replace(/\D+/g, '');
$(this).val(str.replace(/\B(?=(\d{3})+(?!\d))/g, ","));});
</script>
I created a solution using pure javascript.
function onChange(el) {
var newValue = el.value.replace(/,/g, '');
var count = 0;
const last = newValue.substring(newValue.length - 1, newValue.length); // last input value
// check if last input value is real a number
if (!isNumber(last)) {
el.value = el.value.substring(0, el.value.length - 1);
return;
}
newValue = newValue.split('')
.reverse().map((it) => {
var n = it;
if (count > 0 && count % 3 == 0) n = n + ',';
count++;
return n;
})
.reverse().join('')
el.value = newValue
// document.getElementById('value').innerHTML = newValue
}
function isNumber(input) {
return input.match(/\D/g) == undefined;
}
<label>Number</label>
<input id="numbers" onkeyup="onChange(this)">
There are a couple of issues with your code:
It runs once when the page loads, not after that. I added a button to fix that.
The id used in your code does not match the actual id of the input field.
Input fields must be read and written using .val(). .text() works only for divs, spans etc.
Note that the conversion now works one time, after that it fails to properly parse the new text which now contains the comma(s).
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function ShowComma() {
console.clear();
var val = parseInt($("#comma").val());
console.log(val);
val = numberWithCommas(val);
console.log(val);
$("#comma").val(val);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="turnover">Estimated Monthly Card Turnover:</label><br />
<span>£ </span><input type="value" id="comma" maxlength="30" name="turnover" size="10" required>*
<button onclick="ShowComma()">Show Comma</button>
To finalise this I have putgetElementById functions in so that this will work with a wordpress contact form 7. This must be with a text field though as it will not work with the number field as it will now accept commas:
<script>
document.getElementById("averagetrans").onkeyup = function() {onChange(this)};
document.getElementById("Turnover").onkeyup = function() {onChange(this)};
</script>
<script type="text/javascript">
function onChange(el) {
var newValue = el.value.replace(/,/g, '');
var count = 0;
const last = newValue.substring(newValue.length - 1, newValue.length); // last input value
// check if last input value is real a number
if (!isNumber(last)) {
el.value = el.value.substring(0, el.value.length - 1);
return;
}
newValue = newValue.split('')
.reverse().map((it) => {
var n = it;
if (count > 0 && count % 3 == 0) n = n + ','; // put commas into numbers 1000 and over
count++;
return n;
})
.reverse().join('')
el.value = newValue
// document.getElementById('value').innerHTML = newValue
}
function isNumber(input) {
return input.match(/\D/g) == undefined;
}
</script>
I want to mask the text in an input box without changing the actual value. I can not use any plugins.
I am currently doing this - but as you can see the issue is that the actual value is changed on submit. How can I just change the display value?
$("input[name='number']").focusout(function(){
var number = this.value.replace(/(\d{2})(\d{3})(\d{2})/,"$1-$2-$3");
this.value = number;
}
You need two inputs
Two inputs should get the job done. One input will contain the masked text and the other will be a hidden input that contains the real data.
<input type="text" name="masknumber">
<input type="text" name="number" style="display:none;">
The way I approached the masking is to build a function for both masking and unmasking the content so everything stays uniform.
$("input[name='masknumber']").on("keyup change", function(){
$("input[name='number']").val(destroyMask(this.value));
this.value = createMask($("input[name='number']").val());
})
function createMask(string){
return string.replace(/(\d{2})(\d{3})(\d{2})/,"$1-$2-$3");
}
function destroyMask(string){
return string.replace(/\D/g,'').substring(0,8);
}
Working JSFiddle
or also
<input type="text" onkeypress="handleMask(event, 'data: 99/99/9999 99:99 999 ok')" placeholder="data: ok" size=40>
with
function handleMask(event, mask) {
with (event) {
stopPropagation()
preventDefault()
if (!charCode) return
var c = String.fromCharCode(charCode)
if (c.match(/\D/)) return
with (target) {
var val = value.substring(0, selectionStart) + c + value.substr(selectionEnd)
var pos = selectionStart + 1
}
}
var nan = count(val, /\D/, pos) // nan va calcolato prima di eliminare i separatori
val = val.replace(/\D/g,'')
var mask = mask.match(/^(\D*)(.+9)(\D*)$/)
if (!mask) return // meglio exception?
if (val.length > count(mask[2], /9/)) return
for (var txt='', im=0, iv=0; im<mask[2].length && iv<val.length; im+=1) {
var c = mask[2].charAt(im)
txt += c.match(/\D/) ? c : val.charAt(iv++)
}
with (event.target) {
value = mask[1] + txt + mask[3]
selectionStart = selectionEnd = pos + (pos==1 ? mask[1].length : count(value, /\D/, pos) - nan)
}
function count(str, c, e) {
e = e || str.length
for (var n=0, i=0; i<e; i+=1) if (str.charAt(i).match(c)) n+=1
return n
}
}
A more robost version of accepted answer without having two input's which may pollute transmitted form fields and also being aware of key-repetitions and other quirks when pressing a key too long:
<input type="text" name="masknumber" data-normalized="">
and
$("input[name='masknumber']").on("input", function(){ // input event!
let n = destroyMask(this.value);
this.setAttribute("data-normalized", n); // saved as attribute instead
this.value = createMask(n);
})
function createMask(string){
return string.replace(/(\d{2})(\d{3})(\d{2})/,"$1-$2-$3");
}
function destroyMask(string){
return string.replace(/\D/g,'').substring(0, 7); // 7 instead of 8!
}
JSFiddle
I have 4 fields for me to do the calculation, they should add up together and give me the total sum. However, there are some problems with fields when it is empty.
The code and script is below:
<tr id="row">
<td>No. of Dependant(s)</td>
<td><input type="text" id="Dep-main" value="0"></td>
<td><input type="text" id="Dep-joint1" value="0"></td>
<td><input type="text" id="Dep-joint2" value="0"></td>
<td><input type="text" id="Dep-joint3" value="0"></td>
<td><input type="text" id="Total-dep" readonly></td>
</tr>
The script:
<script>
var main = document.getElementById("Dep-main");
var joint1 = document.getElementById("Dep-joint1");
var joint2 = document.getElementById("Dep-joint2");
var joint3 = document.getElementById("Dep-joint3");
var total = document.getElementById("Total-dep");
1
var inputs = Array.prototype.slice.call(document.querySelectorAll("td > input"));
inputs.forEach(function (input) {
input.addEventListener("blur", function () {
// Always supply the second argument to parseInt() (the radix) so you
// dont' get non-base 10 answers.
if (main.value.length === 0) {
total.value = parseFloat(joint1.value) + parseFloat(joint2.value) + parseFloat(joint3.value);
} else if (joint1.value.length === 0) {
total.value = parseFloat(main.value) + parseFloat(joint2.value) + parseFloat(joint3.value);
} else if (joint2.value.length === 0) {
total.value = parseFloat(main.value) + parseFloat(joint1.value) + parseFloat(joint3.value);
} else if (joint3.value.length === 0) {
total.value = parseFloat(main.value) + parseFloat(joint1.value) + parseFloat(joint2.value);
}else{
total.value = parseFloat(main.value) + parseFloat(joint1.value) + parseFloat(joint2.value) + parseFloat(joint3.value);
}
});
});
</script>
However, if there is 2 or more fields are empty, the Total field will appear NaN. Is there any way for me to keep the field as empty and get the total number?
My original idea was flawed in that it would not update the final value if a field was subsequently cleared of a value. Using an object to maintain the values for any element that has received the blur event and then performing a sum calculation of the values seems to work OK.
var total = {};
/* returns numeric value of field or zero if empty etc */
function fieldvalue(id){
var field=document.getElementById( id );
return field.value!='' && field.value.length > 0 && !isNaN( parseFloat( field.value ) ) ? parseFloat( field.value ) : 0;
}
var col=document.querySelectorAll('tr#row > td > input:not([readonly])');
if( col ){
for( var n in col )if( col[ n ].nodeType==1 ){
col[n].addEventListener('blur',function(event){
total[ this.id ]=fieldvalue( this.id );
document.getElementById('Total-dep').value=Object.values(total).reduce(function(a,b){return a+b;});
}.bind( col[n] ),false);
}
}
or, more akin to the original code using Array.prototype.slice
/*
The aim here is to select all input elements that are not marked
as "readonly" as it is these that will be used for the calculations
whilst the "readonly" field is updated programmatically only.
*/
var col=document.querySelectorAll('tr#row > td > input:not([readonly])');
/*
Convert array-like object into a true array in order that we can use
Array.forEach() method which does not work for all browsers when dealing
with HTMLCollections - such as a nodelist
*/
var inputs = Array.prototype.slice.call( col );
inputs.forEach(function(e){
/*
Assign the `onblur` event handler to each of the input elements
- the callback to the event handler will update the `total` object
which is then later processed to calculate the sum of values stored.
*/
e.addEventListener('blur',function(event){
/*
Update the total object with field value
*/
total[ this.id ]=fieldvalue( this.id );
/*
Update the "readonly" field with calculated sum of values
*/
document.getElementById('Total-dep').value=Object.values( total ).reduce(function(a,b){return a+b;});
}.bind( e ),false);
});
Perhaps worth noting is the use of Object.values(obj) - it is not supported by all browsers ( IE, Opera & Safari for instance ) but there are polyfills available here and here
And, I just wrote this - not stringently tested btw
if( typeof( Object.values )!='function' ){
Object.prototype.values=function(obj){
var tmp=[];
var keys=Array.prototype.slice.call( Object.keys( obj ) );
keys.forEach(function( item ){
tmp.push( obj[item] )
});
return tmp;
};
}
i would loop the fields, and if contains something add it.
total.value = 0;
if (main.value.length === 0) {
total.value += parseFloat(main.value);
}
if (join1.value.length === 0) {
total.value += parseFloat(join1.value);
}
if (join2.value.length === 0) {
total.value += parseFloat(join2.value);
}
if (join3.value.length === 0) {
total.value += parseFloat(join3.value);
}
I did not get what you are really after. However, I believe using such checks will lead you to the solution:
var x = $("#someFloatExpectedInput").val();
var y = $("#someIntExpectedInput").val();
if (!isNaN(parseFloat(x))) {
//
}
if (!isNaN(parseInt(y))) {
//
}
You are checking null value in if else statement that why you are getting the error so you need to check separately
Just do like this
var total=0;
if (main.value.length != 0) {
total = total+parseFloat(main.value);
}
if (joint1.value.length != 0) {
total = total+parseFloat(joint1.value);
}
if (joint2.value.length != 0) {
total = total+parseFloat(joint2.value);
}
if (joint3.value.length != 0) {
total = total+parseFloat(joint3.value);
}
total.value = total
It will help you to solve our issue.
Console.log is showing the correct result, but how can I add the same formatting to the input type while typing.
Input type is reset after every comma to zero.
1000 to 1,000
Please Help.
This code is working here
function numberWithCommas(number) {
if (isNaN(number)) {
return '';
}
var asString = '' + Math.abs(number),
numberOfUpToThreeCharSubstrings = Math.ceil(asString.length / 3),
startingLength = asString.length % 3,
substrings = [],
isNegative = (number < 0),
formattedNumber,
i;
if (startingLength > 0) {
substrings.push(asString.substring(0, startingLength));
}
for (i=startingLength; i < asString.length; i += 3) {
substrings.push(asString.substr(i, 3));
}
formattedNumber = substrings.join(',');
if (isNegative) {
formattedNumber = '-' + formattedNumber;
}
document.getElementById('test').value = formattedNumber;
}
<input type="number" id="test" class="test" onkeypress="numberWithCommas(this.value)">
Some notes:
Because you want commas, the type is not a number, it's a string
Because you want to work on the input after you type, it's onkeyup not onkeypressed
I have a solution that does a regex replace for 3 characters with 3 characters PLUS a comma:
var x = "1234567";
x.replace(/.../g, function(e) { return e + ","; } );
// Gives: 123,456,7
i.e. almost the right answer, but the commas aren't in the right spot. So let's fix it up with a String.prototype.reverse() function:
String.prototype.reverse = function() {
return this.split("").reverse().join("");
}
function reformatText() {
var x = document.getElementById('test').value;
x = x.replace(/,/g, ""); // Strip out all commas
x = x.reverse();
x = x.replace(/.../g, function(e) { return e + ","; } ); // Insert new commas
x = x.reverse();
x = x.replace(/^,/, ""); // Remove leading comma
document.getElementById('test').value = x;
}
<input id="test" class="test" onkeyup="reformatText()">
function numberWithCommas(x) {
var real_num = x.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
console.log(real_num);
document.getElementById('test').value = real_num;
}
<input type="number" id="test" onkeypress="numberWithCommas(this.value)">
Check out my fiddle here http://jsfiddle.net/6cqn3uLf/
You'd need another regex to limit to numbers but this will format based on the user's locale - which may be advantageous here.
<input id="mytext" type="text">
$(function () {
$('#btnformat').on('input propertychange paste', function () {
var x = $('#btnformat').val();
$('#btnformat').val(Number(x.replace(/,/g,'')).toLocaleString());
});
});
if jquery is not overhead for your application then you can use
https://code.google.com/p/jquery-numberformatter/
I want to make a webpage that has two text boxes, a Celsius and Fahrenheit box. In between them, there is a convert button which converts Celsius to Fahrenheit and Fahrenheit to Celsius. If there is letters in either box, I want to cancel the converting and an alert pop up saying "Only numbers please!" So far, I haven't figured out how to get the alert and when I type numbers in the Celsius box, it always says the number -18 in the same box. Fahrenheit is fine.
HTML:
<html>
<head>
<title>Temparature Converter</title>
<script type="text/javascript" src="tempconversion.js"></script>
</head>
<body>
Celsius: <input id="c" onkeyup="convert('C')">
<button type="button" id="convert" onclick="convertTemp()">Convert</button>
Fahrenheit: <input id="f" onkeyup="convert('F')">
</body>
</html>
JavaScript:
function convertTemp(degree) {
if (degree == "C") {
F = document.getElementById("c").value * 9 / 5 + 32;
document.getElementById("f").value = Math.round(F);
} else {
C = (document.getElementById("f").value -32) * 5 / 9;
document.getElementById("c").value = Math.round(C);
}
}
Note: I got some code from W3Schools so I think the onkeyup convert is a little funny. If possible, please notify me how it has to change as well as the JavaScript.
There is no need for the onkeyup attributes, since they original code from W3Schools was designed to instantly update values as they were entered.
I did modify the functionality to clear of original value, that way the conversion button can work both ways with a simple code.
Here's a quick JavaScript to do the job:
function convertTemp() {
// Set the initial variables for c (Celsius) and f (Fahrenheit)
var c = document.getElementById('c'), f = document.getElementById('f');
// Test if there is a value for Celsius
if(c.value != '') {
// Set the value for Fahrenheit
f.value = Math.round(c.value * 9 / 5 + 32);
// Clear the value for Celsius
c.value = '';
// If there isn't a value for Celsius
} else {
// Set the value for Celsius
c.value = Math.round((f.value - 32) * 5 / 9);
// Clear the value for Fahrenheit
f.value = '';
}
}
And its accompanying HTML:
Celcius:<input id="c">
Fahrenheit:<input id="f">
<button type="button" id="convert" onclick="convertTemp()">Convert</button>
It can be tested at: http://jsfiddle.net/bhz6uz54/
Something to remember about simple code, like this, there is nothing to verify the supplied values are acceptable. A little regex can act as validation, but how it would be implemented depends on how you want to flag the problem.
I personally hate Do-it Buttons so I'd go with a more dynamic solution:
// Get the Input elements:
var $f = document.getElementById("f");
var $c = document.getElementById("c");
function FC_CF() {
var temp; // Will hold the temperature value
var $targ; // Used to target the element we're not typing into:
if (this.id === "c") { // If we're typing into #c...
$targ = $f; // use #f as target element
temp = (this.value * 9 / 5) + 32; // C2F
} else {
$targ = $c;
temp = (this.value - 32) * 5 / 9; // F2C
}
// Write the result "as we type" in the other ($targ) field:
$targ.value = !isNaN(temp) ? parseFloat(temp.toFixed(1)) : "Err";
// (Above:) temp is a num ? return floated number, else: "Show some error"
}
// Assign input listeners to trigger the above function:
$f.oninput = FC_CF;
$c.oninput = FC_CF;
Celcius: <input id="c">
Fahrenheit: <input id="f">
You can separate the functions which do the temperature conversion as follows i did somw changes in the code.
<p>
<label>Fahrenheit</label>
<input id="outputFahrenheit" type="number" placeholder="Fahrenheit"
oninput="temperatureConverterCelsius(this.value)"
onchange="temperatureConverterCelsius(this.value)" value="">
</p>
<p>Celsius: </p>
<input id="outputCelsius" type="number" placeholder="Celsius"
oninput="temperatureConverterFahrenheit(this.value)"
onchange="temperatureConverterFahrenheit(this.value)" value="">
</p>
<script type=""text/javascript>
function temperatureConverterCelsius(valNum) {
valNum = parseFloat(valNum);
document.getElementById("outputCelsius").value = (valNum-32) / 1.8;
//document.getElementById("outputFahrenheit").value = (valNum*1.8)+32;
}
</script>
</body>
</html>
class Temperature_conversation {
constructor(celsius) {
this.celsius= celsius;
this.fahrenheit= 0;
this.table_begin= -50.0;
this.table_end= 50.0;
this.table_step= 10.0;
console.log('---------------------Conversion--------------------------');
console.log('Celsius fahrenheit');
for(this.celsius = this.table_begin; this.celsius <= this.table_end; this.celsius += this.table_step){
this.fahrenheit = this.celsiusToFahrenhit(celsius);
}
}
celsiusToFahrenhit(c){
const minimun_celsius = -273.15;
if (c < minimun_celsius) {
throw 'O argumento es pequeno';
}
this.celsius = (9.0 / 5.0) * c+ 32;
var res = [this.celsius, this.fahrenheit]
console.table(res);
}
}