Javascript document.getElementByID with condition - javascript

I'm reading from a text file some numbers. Sometimes there's a number 0 and the line below outputs 0, but I don't want to output if the number is "0". Is there a way to change the line below to NOT output/print when the number is "0"? Thanks
document.getElementById('inputText').innerHTML= "(" + parseFloat(output1*2).toFixed(3) + "," + parseFloat(output2*2).toFixed(3) + ")";

You can make a function that checks each value and generates a result based on that, like this:
var getResult = function (num1, num2) {
var result1 = num1 ? (parseFloat(num1) * 2).toFixed(3) : "";
result1 = isNaN(result1) ? "" : result1;
var result2 = num2 ? (parseFloat(num2) * 2).toFixed(3) : "";
result2 = isNaN(result2) ? "" : result2;
var comma = result1 && result2 ? ", " : "";
return `(${result1}${comma}${result2})`;
};
document.getElementById('result').innerHTML += `5, 0 = ${getResult("5")}<br/>`;
document.getElementById('result').innerHTML += `0, 4 = ${getResult("0", "4")}<br/>`;
document.getElementById('result').innerHTML += `3, 2 = ${getResult("3", "2")}<br/>`;
document.getElementById('result').innerHTML += `3, 2 = ${getResult("three", "15.5")}<br/>`;
<div id="result"></div>
Edit: Removed possible NaN-results.

You can replace 0 with nothing using the or operator:
parseFloat(output1*2) || ""
or using a ternary:
output1? parseFloat(output1*2).toFixed(3) : ""

document.getElementById('inputText').innerHTML= "(" + ((parseFloat(output1*2).toFixed(3) + ",") ? parseFloat(1*2).toFixed(3):"") + ((parseFloat(output2*2).toFixed(3)) ? parseFloat(1*2).toFixed(3):"") + ")";

Use if statement to check your number:
Html:
<p id="inputText">
0
</p>
Js:
var output = document.getElementById('inputText').innerHTML;
output = parseFloat(output);
if(output != '0'){
inputText.innerHTML= "(" + (output *2)
.toFixed(3) + "," + (output*2).toFixed(3) + ")";
}
https://jsfiddle.net/b5st3h2m/2/

Related

Replacing null with 0 when summing values

I have a function that sums my values and everything works fine, but only when all inputs have a value entered. However, I would like default to have 0 assigned to it.so that the function works when at least one value is given . How to do it ?.
var DeductiblepercentageM = thisPointer.entity.getValue('number.DeductiblepercentageM[' + i + ']');
var InsuranceLimitM = thisPointer.entity.getValue('number.InsuranceLimitM[' + i + ']');
var insuranceRaitingM = thisPointer.entity.getValue('number.insuranceRaitingM[' + i + ']');
var InsurerNumberM = thisPointer.entity.getValue('number.InsurerNumberM[' + i + ']');
DeductiblepercentageM = DeductiblepercentageM.replace(",", ".");
DeductiblepercentageM = parseFloat(DeductiblepercentageM)
InsuranceLimitM = InsuranceLimitM.replace(",", ".");
InsuranceLimitM = parseFloat(InsuranceLimitM)
insuranceRaitingM = insuranceRaitingM.replace(",", ".");
insuranceRaitingM = parseFloat(insuranceRaitingM)
InsurerNumberM = InsurerNumberM.replace(",", ".");
InsurerNumberM = parseFloat(InsurerNumberM)
//log the outcome of decimal separator change
var positionSum = +(DeductiblepercentageM + InsuranceLimitM +insuranceRaitingM + InsurerNumberM);
jQ('[id="DeductibleM[' + i + ']"]').val(positionSum);
thisPointer.entity.setValue('DeductibleM[' + i + ']', positionSum);
thisPointer.entity.mergeLocal(true);
if (totalSum != "NaN") {
totalSum = +(totalSum + positionSum).toFixed();
}
}
else {
totalSum = "-";
}
According to #Terry
var InsuranceLimitM = thisPointer.entity.getValue('number.InsuranceLimitM[' + i + ']') || 0;
adding || 0 to the end of the code helps and makes the code count right away

Need help understanding why I'm getting not-a-number output with computing imaginary Numbers

function ImaginaryNumbers(realNum, imaginary) {
this.realNum = 0;
this.imaginary = 0;
this.realNum = (typeof realNum === 'undefined') ? this.realNum : parseFloat(realNum);
this.imaginary = (typeof imaginary === 'undefined') ? this.imaginary : parseFloat(imaginary);
}
ImaginaryNumbers.transform = function(num) {
var imaginaryNumbers;
imaginaryNumbers = (num instanceof ImaginaryNumbers) ? num : imaginaryNumbers;
imaginaryNumbers = (typeof num === 'number') ? new ImaginaryNumbers(num, 0) : num;
return imaginaryNumbers;
};
function display_complex(re, im) {
if(im === '0') return '' + re;
if(re === 0) return '' + im + 'i';
if(im < 0) return '' + re + im + 'i';
return '' + re + '+' + im + 'i';
}
function addingComplexNumbers(first, second, third, fourth) {
var num1;
var num2;
num1 = ImaginaryNumbers.transform(document.getElementById("firstComplexNumber").value);
num2 = ImaginaryNumbers.transform(document.getElementById("secondComplexNumber").value);
num3 = ImaginaryNumbers.transform(document.getElementById("thirdComplexNumber").value);
num4 = ImaginaryNumbers.transform(document.getElementById("fourthComplexNumber").value);
var realNum = num1.realNum + num2.realNum + num3.realNum + num4.realNum;
var imaginary = num1.imaginary + num2.imaginary + num3.imaginary + num4.imaginary;
return document.getElementById("result8").innerHTML = display_complex(realNum, imaginary);
}
I try to get the users input but I keep getting NaN + NaNi as the following result. I'm not sure what the problem is. Any help would be appreciated.
You are not getting value from Input as number but as string so use parseInt to get an integer entered.
Current is:
num1 = ImaginaryNumbers.transform(document.getElementById("firstComplexNumber").value);
num2 = ImaginaryNumbers.transform(document.getElementById("secondComplexNumber").value);
num3 = ImaginaryNumbers.transform(document.getElementById("thirdComplexNumber").value);
num4 = ImaginaryNumbers.transform(document.getElementById("fourthComplexNumber").value);
Change to:
num1 = ImaginaryNumbers.transform(parseInt(document.getElementById("firstComplexNumber").value));
num2 = ImaginaryNumbers.transform(parseInt(document.getElementById("secondComplexNumber").value));
num3 = ImaginaryNumbers.transform(parseInt(document.getElementById("thirdComplexNumber").value));
num4 = ImaginaryNumbers.transform(parseInt(document.getElementById("fourthComplexNumber").value));

Convert values - issue

I'm using this code for simple conversion of values between different bases (baseConversion). But there are occurring some issues that I'd love to fix!
"1234" from base 10 to base 3 will get "1200201" and decoded again to base 10 will get "1234" again. So far so good.
Encoding "0001" to base 3 will get "1" and decoding again will get "1" instead of "0001" again. How to fix this?
function convertBase(value, from_base, to_base) {
var range = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/'.split('');
var from_range = range.slice(0, from_base);
var to_range = range.slice(0, to_base);
var dec_value = value.split('').reverse().reduce(function(carry, digit, index) {
if (from_range.indexOf(digit) === -1) throw new Error('Invalid digit `' + digit + '` for base ' + from_base + '.');
return carry += from_range.indexOf(digit) * (Math.pow(from_base, index));
}, 0);
var new_value = '';
while (dec_value > 0) {
new_value = to_range[dec_value % to_base] + new_value;
dec_value = (dec_value - (dec_value % to_base)) / to_base;
}
return new_value || '0';
}
let raw = "1234"
document.body.innerHTML += "raw: " + raw + "<br>"
let encoded = convertBase(raw, 10, 3)
document.body.innerHTML += "encoded: " + encoded + "<br>"
let decoded = convertBase(encoded, 3, 10)
document.body.innerHTML += "decoded: " + decoded + "<br><br>"
raw = "0001"
document.body.innerHTML += "raw: " + raw + "<br>"
encoded = convertBase(raw, 10, 3)
document.body.innerHTML += "encoded: " + encoded + "<br>"
decoded = convertBase(encoded, 3, 10)
document.body.innerHTML += "decoded: " + decoded + "<br><br>"
* {
font-family: Arial;
}
i {
font-weight: bold;
color: gray;
}
<b>Note</b>: "1234" from base 10 to base 3 will get <i>"1200201"</i> and decoded again to base 10 will get <i>"1234"</i>
<br><br> Encoding "0001" to base 3 will get <i>"1"</i> and decoding again will get <i>"1"</i> instead of <i>"0001"</i> again.<br><br>
----------------
<br><br><br><br>
Any help would be very appreciated. Thanks a million in advance!

How to write a javaScript function to enter 2 numbers through prompts and display the sum of those numbers in an alert?

I wanted to display this:
Enter your numbers:
1st :
2nd :
Answer :
I tried doing this:
var a = prompt("A : ", "");
var b = prompt("B : ", "");
function calc(a,b)
{
return a + b;
}
alert ("The addition is =" + calc(a,b);
To do it with only one prompt:
var numbers = prompt("Enter two numbers separated by a semi-colon: ", "");
var a = numbers.split(";")[0];
var b = numbers.split(";")[1];
function calc(a,b)
{
return parseFloat(a) + parseFloat(b);
}
alert ("The addition of " + numbers + " is = " + calc(a,b));
You just need to parse the return from the prompts
var a = prompt("A : ", "");
var b = prompt("B : ", "");
function calc(a,b)
{
return parseFloat(a) + parseFloat(b);
}
alert ("The addition is =" + calc(a,b));

Interesting behavior in my US Number formatting code

I'm trying to make 10 digits look like a US telephone number (i.e.(###) ###-####). My code does accomplish this first goal, but it also does something I can't quite figure out. When typing in the digits, the characters "()" show up before typing any other digits. I want the open parenthesis to appear first and the closing parathesis to appear after entering the third digit. Please don't give me a new solution; try to pin point the issue I'm describing.
<script type="text/javascript">
$('.drumbi-caller-number').live('keydown', function (event) {
if (event.keyCode == 8 || event.keyCode == 37 || event.keyCode == 39) {
} else {
inputval = $(this).val();
var string = inputval.replace(/[^0-9]/g, "");
var first3 = string.substring(0,3);
var next3 = string.substring(3,6);
var next4 = string.substring(6,9);
var string = ("(" + first3 + ")" + next3 + "-" + next4);
$(this).val(string);
}
});
</script>
Here's a jsFiddle that displays this behavior: http://jsfiddle.net/bigthyme/j6kHn/3/
replace keydown with keyup, on keydown the value of the input element isn't updated
also set your string conditionally, only if long enough:
var string = string.length > 2 ? ("(" + first3 + ")" + next3 + "-" + next4) : first3;
here is the code: http://jsfiddle.net/j6kHn/10
btw: you should also replace .live(...) with .on(...) as .live() is deprecated..
You need to check the length of first3 before appending the paren:
var string = ("(" + first3 + ((first3.length>=3)?")":"") + next3 + "-" + next4);
And although not in your question, you can do the same for the hyphen:
var string = ("(" + first3 +
// only append the ) if the you have 3+ chars
((first3.length>=3)?")":"") +
next3 +
// only append the - if the you have 6+ chars
(((first3+next3).length>=6)?"-":"") +
next4);
You should also use .on() instead of live();
See it all working in this jsFiddle
Go with
$('.foo').on('keyup', function (event) {
$(this).val($(this).val().replace(/\D/g, "").replace(/(\d{0,3})(\d{0,3})(\d{0,4}).*/, "($1) $2-$3"));
});
Test this code here.
Try using this code, it should fix all of your issues:
Demo: http://jsfiddle.net/bN6Rh/3/
jQuery:
$('.foo').on('keyup', function(event) {
if (event.keyCode == (8 || 37 || 39)) { }
else {
inputval = $(this).val();
var string = inputval.replace(/[^0-9]/g, "");
var first3 = string.substring(0, 3);
var next3 = " " + string.substring(3, 6);
var next4 = string.substring(6, 10);
if (string.length < 3) { // Less than 3
var string = "(" + first3;
}
else if (string.length > 2 && string.length < 7) { // More than 2 and less than 7
var string = "(" + first3 + ")" + next3;
}
else { // Anything else
var string = "(" + first3 + ")" + next3 + "-" + next4;
}
$(this).val(string);
}
});​
The problem was that you weren't checking the number of characters so as soon as anything was entered it put in ()-, the above code also adds the space you mentioned wanting.
The code could of course be more compressed:
$('.foo').on('keyup', function(e) {
if (e.keyCode == (8 || 37 || 39));
else {
var str = this.value.replace(/[^0-9]/g, "");
var f3 = str.substring(0, 3),
n3 = " " + str.substring(3, 6),
n4 = str.substring(6, 10);
if (str.length<3) str = "(" + f3;
else if (str.length>2&&str.length<7) str="("+f3+")"+n3;
else str="("+f3+")"+n3+"-"+n4;
this.value = str;
}
});​

Categories