Javascript adding integers as a string - javascript

http://unkk9a8915e1.neonz27.koding.io/genetics
Example if you add 6 and 4 with range of 1-2 you get 641 or 642 instead of 11 or 12!
function calculate()
{
var radius1 = document.getElementById("cell1Value").value;
var radius2 = document.getElementById("cell2Value").value;
var radiusAvrg = (radius1 + radius2) / 2;
var childRadius = radius1 + radius2 + (Math.floor(Math.random() * 6) + 1);
console.log(childRadius);
confirm("The child's radius is " + childRadius);
}
<h1>ParentCell01's Radius</h1>
<input type="text" name="cell1Value" id="cell1Value" />
<br />
<h1>ParentCell02's Radius</h1>
<input type="text" name="cell2Value" id="cell2Value"/>
<br />
<button onclick="calculate()">Calculate child's radius.</button>

You need to cast the values to numbers:
var radius1 = +document.getElementById("cell1Value").value;
var radius2 = +document.getElementById("cell2Value").value;

You need to parse your string containing int value before doing a mathematical operation like
var radius1 = parseInt(document.getElementById("cell1Value").value);

Here your function should look like.
function calculate()
{
var radius1 = parseInt(document.getElementById("cell1Value").value);
var radius2 = parseInt(document.getElementById("cell2Value").value);
var radiusAvrg = (radius1 + radius2) / 2;
var childRadius = radius1 + radius2 + (Math.floor(Math.random() * radiusAvrg) + 1);
console.log(childRadius);
confirm("The child's radius is " + childRadius);
}

Related

How do I change the color of each character

I have a problem with some code. I need to change the colour of every succeeding letter as it is being typed into the input
let p = document.querySelector("p");
let input = document.querySelector("input")
function randomColor() {
let r = Math.floor(Math.random() * 256);
let g = Math.floor(Math.random() * 256);
let b = Math.floor(Math.random() * 256);
return "rgb(" + r + " ," + g + " ," + b + ")";
}
input.addEventListener('input',function(){
p.innerText = input.value
for (var i = 0; i < p.length; i++) {
p[i].style.color = randomColor()
}
})
<input type="text" name="">
<p></p>
My problem:
They are not all in different colours eg:I type in hello, each letter should be in a different random colour *************************************************************** PLEASE HELP OUT
You should use innerHTML and add a span with a random color to it every time you input. Also, to get the text you inserted you need to use the event object, something like this:
let p = document.querySelector("p");
let input = document.querySelector("input")
function randomColor() {
let r = Math.floor(Math.random() * 256);
let g = Math.floor(Math.random() * 256);
let b = Math.floor(Math.random() * 256);
return "rgb(" + r + " ," + g + " ," + b + ")";
}
input.addEventListener('input',function(e){
// since e.data can be null when backspacing we remove the last span when that occurs:
if (e.data === null){
p.removeChild(p.lastChild)
}
else {
p.innerHTML = p.innerHTML + "<span style='color:" + randomColor() + "'>" + e.data + "</span>"
}
})
<input type="text" name="">
<p></p>

javascript simple loop calculation

function calc() {
var aa = document.getElementById("aa").value;
var bb = document.getElementById("bb").value;
var cc = document.getElementById("cc").value;
var time = 1;
var dd = document.getElementById("dd").value / 365;
first = 1 + ((bb / 100) / cc);
second = cc * time;
result = aa * Math.pow(first, second);
bb_earn = aa * Math.pow(first, second) - aa;
final = Number(aa) + Number(bb_earn);
var r = "";
var lastTotal = aa;
for (var i = 0; i < dd; i++) {
var newTotal = Number(lastTotal) + Number(bb_earn);
zz = +newTotal;
lastTotal = newTotal;
r += i + 1 + ") " + aa + "---" + zz + "---" + final + "<br/>";
r += "";
}
document.getElementById("table").innerHTML += r;
}
<div> A - <input type="text" id="aa" value="12000" /></div>
<div> B - <input type="text" id="bb" value="20" /></div>
<div> C - <input type="text" id="cc" value="1" /></div>
<div> D - <input type="text" id="dd" value="1825" /></div>
<div> <input type="button" value="Get" onclick="calc();" /></div>
<br/><br/>
<div id="table"></div>
I am trying to loop the default value, 20% of default value and sum of default value plus 20% of default value. In next row, default value should be previous final column sum value. I tried above javascript calculation to achieve the desired result. But, I messed up..
Output result is:
1) 12000---14400---14400
2) 12000---16800---14400
3) 12000---19200---14400
4) 12000---21600---14400
5) 12000---24000---14400
But, Output should be:
1) 12000---2400---14400
2) 14400---2880---17280
3) 17280---3456---20736
4) 20736---4147.20---24883.20
5) 24883.20---4976.60---29859.80
It's a bit hard to figure out what you're trying to achieve with the code, based on what you write. It could be written a lot more simple if you merely wanted to take the previous total and add 20% each time. You don't explain what time variable does and what the #cc element does.
Regardless of that, this should output the result you expect.
function calc() {
var aa = document.getElementById("aa").value;
var bb = document.getElementById("bb").value;
var cc = document.getElementById("cc").value;
var dd = document.getElementById("dd").value / 365;
var r = "";
var lastTotal = Number(aa);
for (var i = 0; i < dd; i++) {
var ratio = ((bb / 100) / cc);
var addition = lastTotal * ratio;
var newTotal = lastTotal + addition;
r += i + 1 + ") " + lastTotal + "---" + addition + "---" + newTotal + "<br/>";
r += "";
lastTotal = newTotal;
}
document.getElementById("table").innerHTML += r;
}
<div> A - <input type="text" id="aa" value="12000" /></div>
<div> B - <input type="text" id="bb" value="20" /></div>
<div> C - <input type="text" id="cc" value="1" /></div>
<div> D - <input type="text" id="dd" value="1825" /></div>
<div> <input type="button" value="Get" onclick="calc();" /></div>
<br/><br/>
<div id="table"></div>
There is nothing wrong with the for next loop
But i guess everything is wrong with your formulas.
<!DOCTYPE HTML>
<html>
<head>
<title>Untitled</title>
</head>
<body>
<div> A - <input type="text" id="aa" value="12000" /></div>
<div> B - <input type="text" id="bb" value="20" /></div>
<div> C - <input type="text" id="cc" value="1" /></div>
<div> D - <input type="text" id="dd" value="1825" /></div>
<div> <input type="button" value="Get" onclick="calc();" /></div>
<br/><br/>
<div id="table"></div>
<script>
function calc(){
var aa = document.getElementById("aa").value*1.0;//ensure that we use numbers and not strings
var bb = document.getElementById("bb").value*1.0;
var cc = document.getElementById("cc").value*1.0;
var time = 1.0;
var dd = document.getElementById("dd").value*1 / 365;
first = 1 + ((bb / 100) / cc);//first = 1.2 bb 20 ,cc 1
second = cc * time; // 1*1=1
// i guess here you make a mistake or choose the wrong test datas
var fact=Math.pow(first, second) // fact = 1.2^1
result = aa * fact; //result 14400 = 12000*1.2;
bb_earn = aa * fact - aa; // bb_earn = 1.2 * 12000 -12000 = .2*12000 =2400
final = aa + bb_earn; //final =12000 + 2400 = again 14400
var zz=0;
var r = "";
var lastTotal = aa;
for (var i = 0; i < dd; i++) {
// as you could see thére is by this numbers NO chance to get something like -4147.20
// there are NO AFTER DIGITS in this calculation
//based on the fact result not possible
var newTotal = Number(lastTotal) + Number(bb_earn);
zz = newTotal;
lastTotal = newTotal;
r += i + 1 + ") " + aa + "---" + zz + "---" + final + "<br/>";
r += "";
}
document.getElementById("table").innerHTML += r;
}
</script>
</body>
</html>

cant figure out how to get the return showing .toFixed(2) amount without error

The script works great for adding items on invoice however i cant figure how to convert the data using .toFixed(2) to show $10.00 instead of 10. I get an error every time I try to add .toFixed(2) . thank you
<script type="text/javascript">
function myFunction() {
var answer = document.getElementById('total');
var x = document.getElementById('itemprice1');
var y = document.getElementById('itemprice2');
var z = document.getElementById('itemprice3');
var w = document.getElementById('itemprice4');
var taxt = document.getElementById('taxtot');
var thetot = document.getElementById('thetot');
// parseFloat converts to values, otherwise you'll concatenate the strings.
answer.value = parseFloat("0" + x.value) + parseFloat("0" + y.value) + parseFloat("0" + z.value) + parseFloat("0" + w.value);
}
function myFunction1() {
var answer = document.getElementById('total');
var taxt = document.getElementById('taxtot');
var thetot = document.getElementById('thetot');
thetot.value = parseFloat("0" + answer.value) + parseFloat("0" + taxt.value);
if (thetot > "0") {
{
//function myFunction2()
var taxt = document.getElementById('taxtot');
var tx1 = document.getElementById('tax1');
var tx2 = document.getElementById('tax2');
var tx3 = document.getElementById('tax3');
var tx4 = document.getElementById('tax4');
var x = document.getElementById('itemprice1');
var y = document.getElementById('itemprice2');
var z = document.getElementById('itemprice3');
var w = document.getElementById('itemprice4');
var answer = document.getElementById('total');
taxt.value = parseFloat("0" + tx1.value) * ("0" + x.value) + parseFloat("0" + tx2.value) * ("0" + y.value) + parseFloat("0" + tx3.value) * ("0" + z.value) + parseFloat("0" + tx4.value) * ("0" + w.value);
}
}
}
</script>
Presumably your controls are in a form, so you can reference them simply using their name in the form. You can also convert strings to numbers using unary +:
function myFunction(formId) {
var f = document.getElementById(formId);
var answer = f.total;
var x = +f.itemprice1.value;
var y = +f.itemprice2.value;
var z = +f.itemprice3.value;
var w = +f.itemprice4.value;
var taxt = f.taxtot;
var thetot = f.thetot;
// Presumably here is where you want to use toFixed
answer.value = '$' + (x + y + z + w).toFixed(2);
}
function to_dollar_string(amount)
{
return "$" + amount.toFixed(2);
}
to_dollar_string(10);
=> "$10.00"
to_dollar_string(10.567);
=> "$10.57"

dividing two variables in javascript

ok, so I am trying to make a midpoint calculator in JavaScript for fun and to practice with the language, The formula is pretty simple, it is just x1 + x2 / 2 and y1 + y2 / 2, I want the user to be able to define the x and y coordinates, and this is what I have come up with:
alert("welcome to nate's midpoint calculator!");
var x1 = prompt("type your first x coordanate!");
var y1 = prompt("excelent!, now your first y coordanate!");
var x2 = prompt("now type your second x coordanate!");
var y2 = prompt("and finally, your last y coordanate!");
var midText = ("your midpoints are: ");
var comma = (",");
var exclam = ("!");
var two = (2)
var x1x2 = (x1 + x2 / two);
var y1y2 = (y2 + y2 / two );
alert(midText + x1x2 + comma + y1y2 + exclam);
for some reason, this is not calculating correctly and turning in wrong answers, go ahead and try it out. it may be some weird misstype from me, I am fairly new to javascript, only having worked with the language for an hour or two. any help would be very much appreciated! thanks in advance!
(x1 + x2 / two)
is dividing then concatenating a string and a number.
Try
((+x1 + +x2) / two)
which uses the prefix + operator to coerce strings to numbers and parenthesizes the low-precedence addition.
You can see this in action by doing
alert(("1" + "0") / 2) // alerts 5 since "1" + "0" == "10"
alert((1 + 0) / 2) // alerts 0.5 since 1 + 0 == 1
perhaps you need
var x1x2 = (parseInt(x1) + parseInt(x2)) / two;
var y1y2 = (parseInt(y2) + parseInt(y2)) / two;
Demo jsFiddle
JS
alert("welcome to nate's midpoint calculator!");
var x1 = prompt("type your first x coordanate!");
var y1 = prompt("excellent!, now your first y coordanate!");
var x2 = prompt("now type your second x coordanate!");
var y2 = prompt("and finally, your last y coordanate!");
var midText = ("your midpoints are: ");
var x1x2 = (+x1 + +x2) / 2;
var y1y2 = (+y2 + +y2) / 2 ;
alert(midText + x1x2 + "," + y1y2 + "!");
The way I would do it (jsFiddle)
HTML
<h1>Welcome to Nate's midpoint calculator!</h1>
<form>
<div>
<label for="x1">X1</label>
<input type="textbox" id="x1" />
<label for="y1">Y1</label>
<input type="textbox" id="y1" />
</div>
<div>
<label for="x2">X2</label>
<input type="textbox" id="x2" />
<label for="y2">Y2</label>
<input type="textbox" id="y2" />
</div>
<div>
<input type="submit" value="Calculate" onclick="Calculate()"/>
</div>
</form>
<div>
<span id="results"></span>
</div>
JS
function Calculate(){
event.preventDefault();
var x1 = parseFloat(document.getElementById('x1').value);
var y1 = parseFloat(document.getElementById('y1').value);
var x2 = parseFloat(document.getElementById('x2').value);
var y2 = parseFloat(document.getElementById('y2').value);
var x1x2 = parseFloat((x1 + +x2) / 2);
var y1y2 = parseFloat((+y2 + +y2) / 2);
document.getElementById("results").innerHTML=("your midpoints are: " + x1x2 + "," + y1y2 + "!");
}
Using KnockoutJS
HTML
<h1>Welcome to Nate's midpoint calculator!</h1>
<div>
<label for="x1">X1</label>
<input type="textbox" id="x1" data-bind="value: x1" />
<label for="y1">Y1</label>
<input type="textbox" id="y1" data-bind="value: y1" />
</div>
<div>
<label for="x2">X2</label>
<input type="textbox" id="x2" data-bind="value: x2" />
<label for="y2">Y2</label>
<input type="textbox" id="y2" data-bind="value: y2" />
</div>
<div>
your midpoints are: <span id="results" data-bind="text: Midpoint"></span>!
</div>
JS
var MidpointCalulatorViewModel = function () {
var self = this;
self.x1 = ko.observable();
self.x2 = ko.observable();
self.y1 = ko.observable();
self.y2 = ko.observable();
self.x1x2 = ko.computed(function () {
return parseFloat((parseFloat(self.x1()) + parseFloat(self.x2())) / 2);
}, self);
self.y1y2 = ko.computed(function () {
return parseFloat((parseFloat(self.y1()) + parseFloat(self.y2())) / 2);
}, self);
self.Midpoint = ko.computed(function () {
return self.x1x2() + "," + self.y1y2();
}, self);
};
ko.applyBindings(new MidpointCalulatorViewModel());
Note you need validation

JS Calculate total on change

I Have this script that calculates the total of some values as the user selects them from dropdowns. Im no expert with JS. Additionally to onchange I would like this code to calculate the value on page load? I would assume it is some copy and paste of this code with an alteration on the function and an if statement?
<script>
$(function() {
$(".DropChange").change(function(){
var valone = $('#ValOne').val();
var valtwo = $('#ValTwo').val();
var valthree = $('#ValThree').val();
var valfour = $('#ValFour').val();
var valfive = $('#ValFive').val();
var valsix = $('#ValSix').val();
var valseven = $('#ValSeven').val();
var valeight = $('#ValEight').val();
var total = ((valone * 1) + (valtwo * 1) + (valthree * 1) + (valfour * 1) + (valfive * 1) + (valsix * 1) + (valseven * 1) + (valeight * 1));
$('#Total').text(total);
});
});
</script>
Probably your simplest option is to stick the current onchange function into another function.
var calculateTotals = function(){
var valone = $('#ValOne').val();
var valtwo = $('#ValTwo').val();
var valthree = $('#ValThree').val();
var valfour = $('#ValFour').val();
var valfive = $('#ValFive').val();
var valsix = $('#ValSix').val();
var valseven = $('#ValSeven').val();
var valeight = $('#ValEight').val();
var total = ((valone * 1) + (valtwo * 1) + (valthree * 1) + (valfour * 1) + (valfive * 1) + (valsix * 1) + (valseven * 1) + (valeight * 1));
$('#Total').text(total);
};
Then change your onchange to
$(".DropChange").change(calculateTotals);
So your $(function(){ ... }); now looks like;
$(function(){
$(".DropChange").change(calculateTotals); // assign event
calculateTotals(); // calculate totals on load
});
Here is what you need:
<script>
(function() {
$(document).ready(function(){
showSum();
});
$(".DropChange").change(function(){
showSum();
}
function showSum(){
var valone = $('#ValOne').val();
var valtwo = $('#ValTwo').val();
var valthree = $('#ValThree').val();
var valfour = $('#ValFour').val();
var valfive = $('#ValFive').val();
var valsix = $('#ValSix').val();
var valseven = $('#ValSeven').val();
var valeight = $('#ValEight').val();
var total = ((valone * 1) + (valtwo * 1) + (valthree * 1) + (valfour * 1) + (valfive * 1) + (valsix * 1) + (valseven * 1) + (valeight * 1));
$('#Total').text(total);
}
}());
</script>

Categories