I have a function where you can click to like, and you kan also click to dislike. How can I make it NOT possible to go to negative number, so that if you click dislike after 0 it stays 0?
function stem(id) {
var antal_stemmer = document.getElementById(id).className;
var nyt_antal_stemmer =+ antal_stemmer + +1;
document.getElementById(id).className = nyt_antal_stemmer;
var indhold = document.getElementsByClassName(id);
var indholdA = indhold[0].innerHTML;
indhold[0].innerHTML = nyt_antal_stemmer + " stemmer";
}
function fjern(id) {
var antal_stemmer = document.getElementById(id).className;
var nyt_antal_stemmer =+ antal_stemmer - +1;
document.getElementById(id).className = nyt_antal_stemmer;
var indhold = document.getElementsByClassName(id);
var indholdA = indhold[0].innerHTML;
indhold[0].innerHTML = nyt_antal_stemmer + " stemmer";
}
You could get the maximum of the value or zero. The result is a number greater or equal zero.
var nyt_antal_stemmer = Math.max(0, antal_stemmer - 1); // - converts the operands to number
Related
I have a JS counter which is working perfectly, but I want to restrict it to two numbers after the decimal point. Right now it can go as high as 9. Any ideas for solutions which won't mess up the rest of the code?
Here's a JSFiddle with my code, also listed below: https://jsfiddle.net/nd252525/26pvd7g3/3/
var INTERVAL_FIRST = 1;
var INCREMENT_FIRST = 0.86;
var START_VALUE_FIRST = 12574343;
var COUNT_FIRST = 0;
window.onload = function () {
var msInterval2 = INTERVAL_FIRST * 1000;
var NOW_FIRST = new Date();
COUNT_FIRST =
parseInt((NOW_FIRST - START_DATE) / msInterval2) * INCREMENT_FIRST +
START_VALUE_FIRST;
document.getElementById("first-ticker").innerHTML = addCommas(COUNT_FIRST);
setInterval(
"COUNT_FIRST += INCREMENT_FIRST; document.getElementById('first-ticker').innerHTML = addCommas(COUNT_FIRST);",
msInterval2
);
};
function addCommas(nStr) {
nStr += "";
x = nStr.split(".");
x1 = x[0];
x2 = x.length > 1 ? "." + x[1] : "";
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, "$1" + "," + "$2");
}
return x1 + x2;
}
Any help is greatly appreciated, thanks :)
You can apply the .toFixed(2) method to your COUNT_FIRST variable to restrict it to 2 digits after the decimal point.
Your code will look like this:
window.onload = function () {
var msInterval2 = INTERVAL_FIRST * 1000;
var NOW_FIRST = new Date();
COUNT_FIRST =
parseInt((NOW_FIRST - START_DATE) / msInterval2) * INCREMENT_FIRST +
START_VALUE_FIRST;
// Add one here
document.getElementById("first-ticker").innerHTML = addCommas(COUNT_FIRST.toFixed(2));
// And one more here
setInterval(
"COUNT_FIRST += INCREMENT_FIRST; document.getElementById('first-ticker').innerHTML = addCommas(COUNT_FIRST.toFixed(2));",
msInterval2
);
};
The code was tested with your provided JSFiddle.
I am trying to do some simple math, using below function. The function is called onChange:
var exposure = $('#exposure').find(":selected").val();
var budget = $('.budget').val();
var ppc = $('.ppc').val();
var value = budget/ppc;
var total2 = Math.floor(value*0.95);
if(exposure == 2){
var dref = 0.0005;
}else if(exposure == 3){
var dref = 0.005;
}else if(exposure == 4){
var dref = 0.001;
}
if(exposure > 1){
var add = dref+ppc;
var value2 = budget/add;
var total2 = Math.floor(value2*0.95);
}
$("#sum").text("" + total2 + " Clicks");
My problem is, that if exposure > 1, the total2 value in #sum will return NaN
What am I doing wrong?
Do a parseInt(value,10) for intergers or parseFloat(value) for float.
JavaScript appends the values if the data type is not a number.
Like:
budget = parseInt(budget,10);
You got to use parseInt or parseFloat. I would say parseFloat something like,
var budget = parseFloat($('.budget').val());
var ppc = parseFloat($('.ppc').val());
var value = parseFloat(budget/ppc);
var total2 = parseFloat((value*0.95));
How to set auto 2 decimal number using value from id input type="text" javascript ?
http://jsfiddle.net/A4wxX/90/
First , fill data eg: 2 into input , it's will update input to 2.00
But not work When i user this
var numb = document.getElementById("int").value;
How can i do ? thank.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script type="text/javascript">
function fn_do() {
var numb = document.getElementById("int").value;
//var numb = 123;
var zzz = numb.toFixed(2);
document.getElementById("int").value = zzz;
}
</script>
<input type="text" id="int" onchange="fn_do()">
You should use parseFloat, because DOM property value is a string, not number.
var zzz = parseFloat(numb).toFixed(2)
And don't use parseInt, because it'll give you an integer, for example parseInt("1.2") will be 1, then toFixed(2) gives you 1.00, while you actually want 1.20 I assume.
One more thing to care is, make sure input content is valid, for example parseFloat('qwer') will give you NaN. So the final code would look like:
var zzz = (parseFloat(numb) || 0).toFixed(2);
Instead of
var zzz = numb.toFixed(2)
Try
var zzz = parseFloat(numb).toFixed(2) //use parseInt() or parsFloat() as shown here.
Your complete will look like this :-
function fn_do() {
var numb = document.getElementById("int").value;
var zz = parseFloat(numb) || 0; //it will convert numb to float if conversion fails it will return 0.
var zzz = zz.toFixed(2);
document.getElementById("int").value = zzz;
}
Fiddle
var decimalForm = parseFloat(Math.round( intNum * 100) / 100).toFixed(2);
alert(decimalForm );
If I'm understanding this correctly, you want whatever number is put into the object with the id 'int' to be automatically converted to a decimal value with two placeholders. You could do something like this:
function convertToDecimal(value) {
var tempValue = Nath.Round(parseFloat(value) * 100);
var returnValue = tempValue * .01;
return returnValue;
}
That would ensure that you always get two decimal places
Exceptions: 1. if tempValue is a multiple of 10, only one decimal will come out
2. if tempValue is a multiple of 100, no decimals will be returned
Solution:
function convertDecimals(convertedValue) {
var tempValue = Nath.Round(parseFloat(value) * 100);
if ((tempValue % 10) == 0) {
if ((tempValue % 100) == 0) { var returnValue = convertedValue + .00; return returnValue; } else {
var returnValue = convertedValue + 0;
return returnValue;
}
}
return '';
}
So maybe the whole cde would look like this
function fn_do() {
var numb = document.getElementById("int").value;
//var numb = 123;
var zzz = convertToDecimal(numb);
zzz = zzz + convertDecimal(zzz);
document.getElementById("int").value = zzz;
}
function convertToDecimal(value) {
var tempValue = Nath.Round(parseFloat(value) * 100);
var returnValue = tempValue * .01;
return returnValue;
}
function convertDecimals(convertedValue) {
var tempValue = Nath.Round(parseFloat(value) * 100);
if ((tempValue % 10) == 0) {
if ((tempValue % 100) == 0) { var returnValue = convertedValue + .00; return returnValue; } else {
var returnValue = convertedValue + 0;
return returnValue;
}
}
return '';
}
im trying to display the 2 decimal point of the 2 total number and minus them but it didnt compute the decimal point. anyone would like to figure this out. thanks.
function calculate() {
var myBox1 = document.getElementById('box1').value;
var myBox2 = document.getElementById('box2').value;
var basicpay = document.getElementById('basicpay');
var myResult = myBox1 * myBox2;
basicpay.value = myResult.toFixed(2);
document.getElementById('both').value = sum() - diff();
}
this is the diff part
function diff() {
var absent = document.getElementById('absent').value;
var tardiness = document.getElementById('tardiness').value;
var sss = document.getElementById('sss').value;
var pagibig = document.getElementById('pagibig').value;
var philhealth = document.getElementById('philhealth').value;
var cashadvances = document.getElementById('cashadvances').value;
var withholdingtax = document.getElementById('withholdingtax').value;
var others = document.getElementById('others').value;
var result =
parseInt(absent) +
parseInt(tardiness) +
parseInt(sss) +
parseInt(pagibig) +
parseInt(philhealth) +
parseInt(cashadvances) +
parseInt(withholdingtax) +
parseInt(others) || 0;
if (!isNaN(result)) {
document.getElementById('totaldeductions').value = result.toFixed(2);
return result;
}
}
this is the sum part
function sum() {
var basicpay = document.getElementById('basicpay').value;
var overtime = document.getElementById('overtime').value;
var regularholiday = document.getElementById('regularholiday').value;
var specialholiday = document.getElementById('specialholiday').value;
var allowanceday = document.getElementById('allowanceday').value;
var monthpay = document.getElementById('monthpay').value;
var others1 = document.getElementById('others1').value;
var result =
parseInt(basicpay) +
parseInt(overtime) +
parseInt(regularholiday) +
parseInt(specialholiday) +
parseInt(allowanceday) +
parseInt(monthpay) +
parseInt(others1) || 0;
if (!isNaN(result)) {
document.getElementById('totalgrosspay').value = result.toFixed(2);
return result;
}
}
In your Sum() and Diff() function, you are working only with integers. Integers are whole numbers only, so will not retain anything after a decimal point. To deal with decimals, you will need to use JavaScript's parseFloat() function. To give an example, in your Sum() function you would change the result calculation to look like the following:
var result =
parseFloat(basicpay) +
parseFloat(overtime) +
parseFloat(regularholiday) +
parseFloat(specialholiday) +
parseFloat(allowanceday) +
parseFloat(monthpay) +
parseFloat(others1) || 0;
This will retain the decimal points in the numbers rather than truncating to whole numbers as the parseInt()
In my code I have a variable myCash, which is printed into an h1 element using javaScript's innerHTML. I found a function online that puts a comma after every third character from the end of the number so that the number is easier to read. I've tried for a couple of hours now sending my variable myCash into the function and then print it on the screen. I CANNOT get it to work.
I've tried just alerting the new variable to the screen after page load or by pressing a button, but I get nothing and the alert doesn't even work. Here's the comma insert function:
function commaFormatted(amount) {
var delimiter = ","; // replace comma if desired
amount = new String(amount);
var a = amount.split('.',2)
var d = a[1];
var i = parseInt(a[0]);
if(isNaN(i)) { return ''; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
var n = new String(i);
var a = [];
while(n.length > 3)
{
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if(n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
if(d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
amount = minus + amount;
return amount;
}
now when I want my variable to change I've tried it a few different ways including this:
var newMyCash = commaFormatted(myCash);
alert(newMyCash);
and this:
alert(commaFormatted(myCash);
Where of course myCash equal some large number;
This does absolutely nothing! What am I doing wrong here??
Also,
Try this as a drop in replacement and try alerting the response:
http://phpjs.org/functions/number_format:481
Do you see any errors in the console of your browser (usually f12)?
This is not my function, but I hope it helps you.
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
Usage:
var newMyCash = addCommas( myCash ); alert( newMyCash );
Source: http://www.mredkj.com/javascript/nfbasic.html
You are most likely not passing in a number that contains a decimal, which the function expects.
Working Demo