so I've got a bit of the problem. I am trying to make a function in wich : human clicks on input box with mouse and types some random numbers in bytes and that number should be convert and shown in two other boxes such as MegaBytes and KiloBytes. So my problem is that Javascript shows me error :
Cannot set property 'value' of null
at convert (script.js:7)
at HTMLInputElement.onkeyup
here is my code so far:
function convert(inputas)
{
var i;
if(inputas == "B")
{
i = document.getElementById("baitas").value / 1000;
document.getElementById("kiloBaitas").value = i;
}
else if(inputas == "KB")
{
i = document.getElementById("kiloBaitas").value * 1024;
document.getElementById("baitas").value = i.toFixed(2);
}
}
HTML code:
<input type="text" id="baitas" onkeyup="convert('B')placeholder="Bits">
<input type="text" id="kilobaitas"
`onkeyup="convert('KB')"placeholder="Kilobits">
<input type="text" id="megabaitas" onkeyup="convert('MB')"
placeholder="Mbits">
<script src="script.js"></script>
when comparing your javascript with the html. the kilobaitis element is not spelt with a consistent case.
JavaScript is case sensitive.
function convert(inputas) {
var i;
if (inputas == "B") {
i = document.getElementById("baitas").value / 1000;
document.getElementById("kilobaitas").value = i;
} else if (inputas == "KB") {
i = document.getElementById("kiloBaitas").value * 1024;
document.getElementById("baitas").value = i.toFixed(2);
}
}
<input type="text" id="baitas" onkeyup="convert('B')" placeholder=" Bits ">
<input type="text " id="kilobaitas" onkeyup="convert('KB')" placeholder="Kilobits ">
<input type="text " id="megabaitas" onkeyup="convert('MB')" placeholder="Mbits ">
(function() {
var elems = [],
elemsId = ['baitas','kilobaitas','megabaitas'];
function fix(a){ return ( a * 100 | 0 ) / 100 }
function convert(inputas)
{
var i;
switch(inputas)
{
case 0:
i = elems[0].value;
elems[1].value = fix( i / 1024 );
elems[2].value = fix( i / 1048576 );
break;
case 1:
i = elems[1].value;
elems[0].value = i * 1024;
elems[2].value = fix( i / 1024 );
break;
case 2:
i = elems[2].value;
elems[0].value = i * 1048576;
elems[1].value = i * 1024;
break;
}
}
for (var i=0; i < elemsId.length; i++)
{
elems[i] = document.getElementById( elemsId[i] );
elems[i].addEventListener('keyup', convert.bind(null, i) )
}
}());
<input type="text" id="baitas" placeholder=" Bits">
<input type="text" id="kilobaitas" placeholder=" Kilobits">
<input type="text" id="megabaitas" placeholder=" Mbits">
Related
I am trying to set the number of decimals of many inputs by using a specific input.
Here is what I am doing:
window.oninput = function(event) {
var campo = event.target.id;
// DECIMALS
if (campo == "decimalTemp") {
var i = decimalTemp.value;
ºC.value.toFixed = i;
ºK.value.toFixed = i;
ºF.value.toFixed = i;
ºRa.value.toFixed = i;
}
// TEMPERATURE
if (campo == "ºC") {
ºK.value = (ºC.value * 1 + 273.15).toFixed(i);
ºF.value = (ºC.value * 1.8 + 32).toFixed(i);
ºRa.value = ((ºC.value * 1 + 273.15) * 1.8).toFixed(i);
} else if (campo == "ºK") {
ºC.value = (ºK.value * 1 - 273.15).toFixed(2);
ºF.value = (ºK.value * 1.8 - 459.889).toFixed(2);
ºRa.value = (ºK.value * 1.8).toFixed(2);
} else if (campo == "ºF") {
ºC.value = ((ºF.value * 1 - 32) / 1.8).toFixed(2);
ºK.value = ((ºF.value * 1 + 459.67) / 1.8).toFixed(2);
ºRa.value = (ºF.value * 1 + 459.67).toFixed(2);
} else if (campo == "ºRa") {
ºC.value = (ºRa.value / 1.8 - 273.15).toFixed(2);
ºK.value = (ºRa.value / 1.8).toFixed(2);
ºF.value = (ºRa.value * 1 - 459.67).toFixed(2);
}
};
<h3>Temperature <input type="number" min="0" max="12" value="0" id="decimalTemp" name="decimal" placeholder="Decimal"> <small>Decimals<small></h3>
Celsius (ºC) <input id="ºC" type="number" min="-273.15" value="20">
<br> Kelvin (K) <input id="ºK" type="number" min="0" value="293">
<br> Farenheit (ºF) <input id="ºF" type="number" min="-459.67" value="68">
<br> Rankine (ºRa) <input id="ºRa" type="number" min="0" value="528">
In summary, I would like to know if this construction is correct:
var i = decimalTemp.value;
ºC.value.toFixed = i;
I already tried something like:
ºC.value.toFixed(i);
But didn't work. Any idea where am I wrong?
I am building a website and I want to do calculations based on information provided. I obviously need to have information provided in two out of the three fields to calculate the third's value.
The three fields are:
Price Per Gallon
Gallons Bought
Total Sale
I obviously know that I can calculate the amount of gas bought by dividing the Total Sale amount by the Price Per Gallon.
However I want to calculate based on whatever two fields are entered. I am trying to find out the best way to do this.
I know this much:
Check to see which fields are empty
Determine which type of calculation to make
Here is what I have so far:
<form>
<input type="number" id="totalSale" placeholder="Total Sale Amount" class="calculate" />
<input type="number" id="gallonPrice" placeholder="Price Per Gallon" class="calculate" />
<input type="number" id="gallons" placeholder="Gallons" class="calculate" />
</form>
<script>
var e = document.getElementsByClassName("calculate");
function calc(){
var sale_amt = document.getElementById("totalSale");
var ppg = document.getElementById("gallonPrice");
var gallons = document.getElementById("gallons");
if (sale_amt || ppg !== null) {
var calc_gallons = sale_amt.value / ppg.value;
gallons.value = calc_gallons.toFixed(3);
}
}
for (var i = 0; i < e.length; i++) {
e[i].addEventListener('keyup', calc, false);
}
</script>
the logic should take into consideration which element is currently being entered (that will be this in calc). Also, you need to take into consideration what happens when all three have values, and you change one ... which of the other two should be changed?
See if this works for you
var sale_amt = document.getElementById("totalSale");
var ppg = document.getElementById("gallonPrice");
var gallons = document.getElementById("gallons");
function calc(){
var els = [sale_amt, ppg, gallons];
var values = [sale_amt.value, ppg.value, gallons.value];
var disabledElement = els.find(e=>e.disabled);
var numValues = els.filter(e => e.value !== '' && !e.disabled).length;
var calc_gallons = function() {
gallons.value = (values[0] / values[1]).toFixed(3);
};
var calc_ppg = function() {
ppg.value = (values[0] / values[2]).toFixed(3);
};
var calc_sale = function() {
sale_amt.value = (values[1] * values[2]).toFixed(2);
};
if (numValues < 3) {
if (numValues == 1 && disabledElement) {
disabledElement.disabled = false;
disabledElement.value = '';
disabledElement = null;
}
els.forEach(e => e.disabled = e == disabledElement || (numValues == 2 && e.value === ''));
}
disabledElement = els.find(e=>e.disabled);
switch((disabledElement && disabledElement.id) || '') {
case 'totalSale':
calc_sale();
break;
case 'gallonPrice':
calc_ppg();
break;
case 'gallons':
calc_gallons();
break;
}
}
var e = document.getElementsByClassName("calculate");
for (var i = 0; i < e.length; i++) {
e[i].addEventListener('keyup', calc, false);
e[i].addEventListener('change', calc, false);
}
I am new to JavaScript and need help with code optimization. I am pretty sure there are some ways to create "classes" to run my code better and more efficient.
Here is the link to my jsfiddle demo version: JSFiddle Demo
<form id="tyreForm">
<div id="currentTyre">
<h2>Current Tyre Size</h2>
<div id="errorDisplay"></div>
<input type="number" id="sectionWidth"> /
<input type="number" id="aspectRatio"> R
<input type="number" id="rimDiameter">
<p>Sidewall: <span class="output"></span></p>
<p>Width: <span class="output"></span></p>
<p>Diameter: <span class="output" id="fullDiameter"></span></p>
<p>Circumference: <span class="output"></span></p>
<p>Reverse / Mile: <span class="output"></span></p>
</div>
<div id="newTyre">
<h2>New Tyre Size</h2>
<input type="number" id="newSectionWidth"> /
<input type="number" id="newAspectRatio"> R
<input type="number" id="newRimDiameter">
<p>Sidewall: <span class="output"></span></p>
<p>Width: <span class="output"></span></p>
<p>Diameter: <span class="output" id="newFullDiameter"></span></p>
<p>Circumference: <span class="output"></span></p>
<p>Reverse / Mile: <span class="output"></span></p>
</div>
<div id="result">
<h2>Tyre difference</h2>
<p>Diameter Difference(%): <span id="diameterDifference"></span></p>
</div>
<button type="submit">Calculate</button>
</form>
document.getElementById('tyreForm').addEventListener('submit', function(e) {
e.preventDefault();
var sw = this.sectionWidth.value;
var ar = this.sectionWidth.value;
var rd = this.sectionWidth.value;
var nsw = this.newSectionWidth.value;
var nar = this.newAspectRatio.value;
var nrd = this.newRimDiameter.value;
/* Form Validation Starts */
var errorDisplay = document.getElementById('errorDisplay');
errorDisplay.style.display = 'block';
if (sw == '' || ar == '' || rd == '') {
errorDisplay.style.color = "red";
errorDisplay.textContent = "Error: Please fill all the fields";
return false;
}
if (sw == 0 || ar == 0 || rd == 0) {
errorDisplay.style.color = "red";
errorDisplay.textContent = "Error: Please check your input fields. 0 is not valid";
return false;
}
/* Form Validation Finishes */
this.getElementsByClassName("output")[0].textContent = sidewall(sw, ar).toFixed(2);
this.getElementsByClassName("output")[1].textContent = width(sw, ar, rd).toFixed(2);
this.getElementsByClassName("output")[2].textContent = diameter(sw, ar, rd).toFixed(2);
this.getElementsByClassName("output")[3].textContent = circumference(sw, ar, rd).toFixed(2);
this.getElementsByClassName("output")[4].textContent = reverseMile(sw, ar, rd).toFixed(2);
this.getElementsByClassName("output")[5].textContent = sidewall(nsw, nar).toFixed(2);
this.getElementsByClassName("output")[6].textContent = width(nsw, nar, nrd).toFixed(2);
this.getElementsByClassName("output")[7].textContent = diameter(nsw, nar, nrd).toFixed(2);
this.getElementsByClassName("output")[8].textContent = circumference(nsw, nar, nrd).toFixed(2);
this.getElementsByClassName("output")[9].textContent = reverseMile(nsw, nar, nrd).toFixed(2);
var fd = document.getElementById('fullDiameter').textContent;
var nfd = document.getElementById('newFullDiameter').textContent;
document.getElementById('diameterDifference').textContent = diameterDifference(fd, nfd);
}, false);
/* All functions */
function sidewall(sw, ar) {
return ((sw * (ar/100)) / 25.4);
}
function width(sw, ar) {
return (sw / 25.4);
}
function diameter(sw, ar, rd) {
return ((sidewall(sw, ar) * 2) + parseFloat(rd));
}
function circumference(sw, ar, rd) {
return (((((sw * (ar/100)) / 25.4) * 2)+ parseInt(rd)) * 3.14);
}
function reverseMile(sw, ar, rd) {
return (63360 / (((((sw * (ar/100)) / 25.4) * 2)+ parseInt(rd)) * 3.14));
}
function diameterDifference(fd, nfd) {
return fd * nfd; // Just dummy formula
}
The main idea is:
Have two forms where people can enter their tire sizes.
If only the first form filled with data - calculation happens only in the first form
If both forms are filled with data - both forms' calculations are proceeded plus some data is passed to third form
Please check jsfiddle for more information.
Thanks in advance!
Best
You should create a Tyre prototype that takes sectionWidth, aspectRatio, and rimDiameter in the "constructor" and more all of your functions into that prototype. Doing this will simplify the logic of your code and will help you adhere to the principles of DRY (don't repeat yourself).
var Tyre = function(sectionWidth, aspectRatio, rimDiameter) {
this.sw = sectionWidth;
this.ar = aspectRatio;
this.rd = rimDiameter;
this.isEmpty = function() {
return this.sw === '' || this.ar === '' || this.rd === '';
};
this.isZero = function() {
return this.sw == 0 || this.ar == 0 || this.rd == 0;
};
this.width = function() {
return this.sw / 25.4;
};
this.sidewall = function() {
return this.width() * this.ar / 100;
};
this.diameter = function() {
return 2 * this.sidewall() + parseFloat(this.rd);
};
this.circumference = function() {
return this.diameter() * Math.PI;
};
this.reverseMile = function() {
return 63360 / this.circumference();
};
this.diameterDifference = function(other) {
return this.diameter() * other.diameter();
};
};
document.getElementById('tyreForm').addEventListener('submit', function(e) {
e.preventDefault();
var currentTyre = new Tyre(this.sectionWidth.value, this.aspectRatio.value, this.rimDiameter.value);
var newTyre = new Tyre(this.newSectionWidth.value, this.newAspectRatio.value, this.newRimDiameter.value);
/* Form Validation Starts */
var errorDisplay = document.getElementById('errorDisplay');
errorDisplay.style.display = 'block';
if (currentTyre.isEmpty()) {
errorDisplay.style.color = "red";
errorDisplay.textContent = "Error: Please fill all the fields";
return false;
}
if (currentTyre.isZero()) {
errorDisplay.style.color = "red";
errorDisplay.textContent = "Error: Please check your input fields. 0 is not valid";
return false;
}
/* Form Validation Finishes */
this.getElementsByClassName("output")[0].textContent = currentTyre.sidewall().toFixed(2);
this.getElementsByClassName("output")[1].textContent = currentTyre.width().toFixed(2);
this.getElementsByClassName("output")[2].textContent = currentTyre.diameter().toFixed(2);
this.getElementsByClassName("output")[3].textContent = currentTyre.circumference().toFixed(2);
this.getElementsByClassName("output")[4].textContent = currentTyre.reverseMile().toFixed(2);
if (newTyre.isEmpty() || newTyre.isZero())
return;
this.getElementsByClassName("output")[5].textContent = newTyre.sidewall().toFixed(2);
this.getElementsByClassName("output")[6].textContent = newTyre.width().toFixed(2);
this.getElementsByClassName("output")[7].textContent = newTyre.diameter().toFixed(2);
this.getElementsByClassName("output")[8].textContent = newTyre.circumference().toFixed(2);
this.getElementsByClassName("output")[9].textContent = newTyre.reverseMile().toFixed(2);
document.getElementById('diameterDifference').textContent = currentTyre.diameterDifference(newTyre);
}, false);
Here is the javascript for calculating the price of the item the problem is that
whenever the price is 4 digits the value that return is NaN.
here's my hidden field for the price:
<input type="hidden" name="price" id="price"class="price" value="4500"readonly >
here's for my quantity field
<input type="number" name="quant" id="quant" value="2" />
here's for my shipment fee
<select id="shipment" onchange="myFunction3()" name="shipment2" disabled>
<option value="100" data-quantity="1">1 for 100 pesos </option>
</select
here's for the total price
<input type="text" id="demo" name="total_price" style="margin-top:10px;margin-left:5px;" readonly>
Script for changing the value of shipment
<script type="text/javascript">
document.getElementById('quant').addEventListener("keyup", function(){
var value = parseInt(this.value, 20),
selectEle = document.getElementsByTagName('select')[0],
options = selectEle.options,
selectedNum = 0;
for(var i = 0; i < options.length; i++) {
//checking the exact string with spaces (" " + value + " ")
if(options[i].textContent.indexOf(" " + value + " ") > -1) {
selectedNum = i;
}
}
selectEle.selectedIndex = selectedNum ? selectedNum : 0;
}, false);
</script>
Calculating all the values
function myFunction3() {
var y= document.getElementById("shipment").value;
return y;
}
<script>
$("#price,#quant,#shipment").keyup(function () {
if(+myFunction3() =="" )
{
$('#demo').val(0);
}
else if($('#trigger')=="checked") //this is the problem
{
$('#demo').val($('#price').val() * $('#quant').val() ;
}
else
{
$('#demo').val($('#price').val() * $('#quant').val() + +myFunction3());
}
});
</script>
Not sure if this was just typed incorrectly in here, but you have a syntax error (missing closing parenthesis) near the problem area:
$('#demo').val($('#price').val() * $('#quant').val() ;
Should be:
$('#demo').val($('#price').val() * $('#quant').val());
I think it would be much better to ensure you aren't working with strings before you do math on them:
var price = parseInt($('#price').val(), 10);
var quantity = parseInt($('#quant').val(), 10);
$('#demo').val(price * quantity);
You could go further and ensure that neither of them are NaN prior to working with them:
var price = parseInt($('#price').val(), 10);
var quantity = parseInt($('#quant').val(), 10);
if(!isNaN(price) && !isNaN(quantity)) {
$('#demo').val(price * quantity);
} else {
alert('Please enter numbers only!');
}
I'm writing a script where I need to get the total of two calculations and determine the total quote. The problem is I cannot get them to work when it comes to add them together. Bear in mind I'm a newbie and the code might no be fully optimized but I'm sure you will get the point. Any improvements on the code are more than welcome.
<div>
<fieldset>
<legend>Printing</legend>
Number of color pages:<input type="text" id="color" placeholder="Color Pages" onchange="printing();" onchange = "binding();" />
<input type="text" id="colorprice" readonly="readonly" /><br />
Number of black and white pages:<input type="text" id="black" placeholder="Black and White Pages" onchange="printing();" onchange = "binding();" />
<input type="text" id="blackprice" readonly="readyonly" /><br />
Total Pages:<input type="text" id="pages_total" readonly="readonly" /> <input type="text" id="sum_pages" readonly="readonly" onchange = "suming();"/>
</fieldset>
</div>
<div>
<fieldset>
<legend>Binding</legend>
Number of Hardbooks: <input type="text" id="books" placeholder="Number of Hardbooks" onchange="binding();" />
<input type="text" id="books_price" readonly="readonly" /><br />
Number of Softbacks: <input type="text" id="softback" placeholder="Number of Softbacks" onchange="binding();" />
<input type="text" id="soft_price" readonly="readonly" /><br />
Total Bindings: <input type="text" id="total_bindings" readonly="readonly" /><input type "text" id="total_price" readonly="readonly" />
</fieldset>
</div>
<p>Final quote:<input type="text" readonly="readonly" id="quote" /></p>
function printing() {
var blackPrice;
var colorPrice;
var printBlack = new Array(0.10, 0.08, 0.06, 0.05);
var printColor = new Array(0.40, 0.35, 0.30, 0.25);
var colorPages = parseInt(document.getElementById("color").value);
var blackPages = parseInt(document.getElementById("black").value);
if (colorPages < 11) {
colorPrice = colorPages * printColor[0];
}
else if (colorPages >= 11 && colorPages < 51){
colorPrice = colorPages * printColor[1];
}
else if (colorPages >= 51 && colorPages < 101){
colorPrice = colorPages * printColor[2];
}
else {
colorPrice = colorPages * printColor[3];
}
if (blackPages < 11) {
blackPrice = blackPages * printBlack[0];
}
else if (blackPages >= 11 && colorPages < 51){
blackPrice = blackPages * printBlack[1];
}
else if (blackPages >= 51 && colorPages < 101){
blackPrice = blackPages * printBlack[2];
}
else {
blackPrice = blackPages * printBlack[3];
}
var pagesTotal = colorPages + blackPages;
var printSum = blackPrice + colorPrice;
document.getElementById("colorprice").value = "$" + colorPrice.toFixed(2);
document.getElementById("blackprice").value = "$" + blackPrice.toFixed(2);
document.getElementById("sum_pages").value = "$" + printSum.toFixed(2);
document.getElementById("pages_total").value = pagesTotal;
return printSum;
}
function binding(){
var softbackPrice;
var hardbookPrice;
var hardBooks = new Array(37.50, 23.50);
var softBacks = new Array(3.75, 4.00, 4.25, 4.50, 4.75, 5.00, 5.25);
var noBooks = parseInt(document.getElementById("books").value);
var noSoftBacks = parseInt(document.getElementById("softback").value);
var colorPages = parseInt(document.getElementById("color").value);
var blackPages = parseInt(document.getElementById("black").value);
var totalPages = colorPages + blackPages;
if (noBooks == 1) {
hardbookPrice = hardBooks[0];
}
else {
hardbookPrice = (hardBooks[1] * (noBooks - 1)) + hardBooks[0];
}
if (totalPages <= 50) {
softbackPrice = softBacks[0] * noSoftBacks;
}
else if (totalPages > 50 && totalPages <= 100) {
softbackPrice = softBacks[1] * noSoftBacks;
}
else if (totalPages > 100 && totalPages <= 150) {
softbackPrice = softBacks[1] * noSoftBacks;
}
else if (totalPages > 150 && totalPages <=200) {
softbackPrice = softBacks[2] * noSoftBacks;
}
else if (totalPages > 200 && totalPages <= 250) {
softbackPrice = softBacks[3] * noSoftBacks;
}
else if (totalPages > 250 && totalPages <= 300) {
softbackPrice = softBacks[4] * noSoftBacks;
}
else if (totalPages > 300 && totalPages <= 350) {
softbackPrice = softBacks[5] * noSoftBacks;
}
else {
softbackPrice = softBacks[6] * noSoftBacks;
}
var totalPrice = softbackPrice + hardbookPrice;
var bindingsTotal = noSoftBacks + noBooks;
document.getElementById("books_price").value = "$" + hardbookPrice.toFixed(2);
document.getElementById("soft_price").value = "$" + softbackPrice.toFixed(2);
document.getElementById("total_bindings").value = bindingsTotal;
document.getElementById("total_price").value = "$" + totalPrice.toFixed(2);
return totalPrice;
}
function totalSum() {
var totalPrinting = printing();
var totalBinding = binding();
var subtotal = totalPrinting + totalBinding;
document.getElementIdBy("quote").value = subtotal;
}
Here is the working solution. http://jsfiddle.net/UHnRL/2/
= is missing for type in the below markup
<input type "text" id="total_price" readonly="readonly" />
It works for me (mostly): http://jsfiddle.net/UHnRL/
There is an issue with the first onchange calculation, because the other number of pages is NaN after you do the parseInt. You should default it to zero if the text box is blank.
You can use the isNaN[MDN] function to resolve the calculation issue:
var colorPages = parseInt(document.getElementById("color").value);
var blackPages = parseInt(document.getElementById("black").value);
if (isNaN(colorPages))
{
colorPages = 0;
}
if (isNaN(blackPages))
{
blackPages = 0;
}