JavaScript Code Optimization - Creating Reusable Classes - javascript

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);

Related

I remove a file that I uploaded, I got a error

When I remove a file that I uploaded, I got a error. That is js:42 Uncaught TypeError: Cannot read property 'removeChild' of null. I have to use removeChild and var for IE. Is there a good way to fix the error?
html
<form action="" enctype="multipart/form-data" class="page_form">
<label class="ui_upload upload_label" for="upload-doc">
<input type="file" name="file" id="upload-doc"
accept=".pdf,.doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
multiple />
<span class="btn sm label upload_btn">upload file</span>
</label>
<div class="upload_documents_wrap visually_hide">
<div class="upload_documents"> </div>
</div>
<div class="visually_hide" id="upload-file">
<div class="upload_info shadow light upload_file">
<span class="tit sm file_name"> </span>
<span class="tit sm file_size"> </span>
<button class="file_remove" type="button">Remove</button>
</div>
</div>
<button type="submit" class="btn sm">submit</button>
</form>
js
(function () {
var formElement = document.querySelector(".page_form");
var fileChooserEl = formElement.querySelector('.upload_label input[type="file"]');
var uploadDocumentsWrap = formElement.querySelector(".upload_documents_wrap");
var uploadDocuments = uploadDocumentsWrap.querySelector(".upload_documents");
var templateItemParent = document.querySelector("#upload-file");
var templateItem = templateItemParent.querySelector(".upload_file");
var uploadFiles = [];
var myFileList = [];
var onFileChooserChange = function () {
for (var i = 0; i < fileChooserEl.files.length; i++) {
var position = templateItem.cloneNode(true);
var uploadFileName = position.querySelector(".file_name");
var uploadFileSize = position.querySelector(".file_size");
var uploadFileRemove = position.querySelector(".file_remove");
var fileName = fileChooserEl.files[i].name.toLowerCase();
uploadDocumentsWrap.classList.remove("visually_hide");
uploadFileName.textContent = fileName; // file size
var suffix = "bytes";
var size = fileChooserEl.files[i].size;
if (size >= 1024 && size < 1024000) {
suffix = "KB";
size = Math.round(size / 1024 * 100) / 100;
} else if (size >= 1024000) {
suffix = "MB";
size = Math.round(size / 1024000 * 100) / 100;
}
uploadFileSize.textContent = size + suffix;
uploadFileRemove.addEventListener("click", function (evt) {
evt.preventDefault();
myFileList = myFileList.filter(function (item) {
return item.name.toLowerCase() !== uploadFileRemove.previousElementSibling.textContent;
});
console.log(myFileList);
var index = uploadFiles.indexOf(evt.target.parentNode);
uploadFileRemove.parentNode.parentNode.removeChild(uploadFileRemove.parentNode);
uploadFiles.splice(index, 1);
myFileList.splice(index, 1);
console.log(index);
if (!uploadFiles.length) {
uploadDocumentsWrap.classList.add("visually_hide");
}
});
uploadDocuments.appendChild(position);
uploadFiles.push(position);
myFileList.push(fileChooserEl.files[i]);
}
fileChooserEl.value = "";
};
console.log(uploadFiles);
var getFormData = function () {
var data = new FormData(formElement);
for (var i = 0; i < myFileList.length; i += 1) {
data.append(fileChooserEl.name, myFileList[i]);
}
return data;
};
fileChooserEl.addEventListener("change", onFileChooserChange);
})();
The error is on this line:
uploadFileRemove.parentNode.parentNode.removeChild(uploadFileRemove.parentNode);
I debugged the code and find that you removed wrong file every time when clicking the "Remove" button. It's easier and more clear to identify which file to remove using index. I edit the code like this and it works well:
...
var index = uploadFiles.indexOf(evt.target.parentNode);
//edit
var removefile = document.querySelectorAll(".upload_info")[index];
uploadDocuments.removeChild(removefile);
//uploadFileRemove.parentNode.parentNode.removeChild(uploadFileRemove.parentNode);
uploadFiles.splice(index, 1);
myFileList.splice(index, 1);
console.log(index);
...
Result:

How to make Feedback disappear with user action in Javascript?

What do I need to add to the code, so that when the user clicks the button New or starts typing in the inputfield "userAnswer" for a second try, the Feedback disappears.
But the feedback should always appear when user clicks check
This is the simplified version of the code:
function F1() {
Z1 = document.getElementById("Z1");
Z2 = document.getElementById("Z2");
rZ1 = Math.floor((Math.random() * 10));
rZ2 = Math.floor((Math.random() * 10));
Z1.innerHTML = rZ1;
Z2.innerHTML = rZ2;
var operators1 = ['+', '-'];
oper1 = document.getElementById("operator1");
op1 = operators1[Math.floor(Math.random() * 2)];
oper1.innerHTML = op1;
rnd = parseFloat(eval(rZ1 + op1 + rZ2));
answer.innerHTML = rnd;
}
function F2() {
antw = parseFloat(document.getElementById("userAnswer").value);
feedBack = document.getElementById("feedBack");
ant = document.getElementById("answer").textContent;
{
if (antw == ant) {
feedBack.textContent = "good";
} else {
feedBack.textContent = "bad";
}
}
};
<button onclick="F1()"> New </button>
<label id="Z1"> </label>
<label id="operator1"> </label>
<label id="Z2"> </label>
= <input id="userAnswer" type=text>
<button onclick="F2()">check</button>
<p id="feedBack"> </p>
<p> <label id="answer"></label> </p>
I added a function at the end of the code to disappear with feedBack and a line was added in F1 and F2 to display and disappear with feedBack (I added a comment on those lines)
function F1() {
Z1 = document.getElementById("Z1");
Z2 = document.getElementById("Z2");
rZ1 = Math.floor((Math.random() * 10));
rZ2 = Math.floor((Math.random() * 10));
Z1.innerHTML = rZ1;
Z2.innerHTML = rZ2;
var operators1 = ['+', '-'];
oper1 = document.getElementById("operator1");
op1 = operators1[Math.floor(Math.random() * 2)];
oper1.innerHTML = op1;
rnd = parseFloat(eval(rZ1 + op1 + rZ2));
answer.innerHTML = rnd;
document.querySelector('p#feedBack').style.display = 'none' // add this
document.querySelector('#userAnswer').value = ''
}
function F2() {
antw = parseFloat(document.getElementById("userAnswer").value);
feedBack = document.getElementById("feedBack");
ant = document.getElementById("answer").textContent;
{
if (antw == ant) {
feedBack.textContent = "good";
} else {
feedBack.textContent = "bad";
}
}
document.querySelector('p#feedBack').style.display = 'block' // add this
};
document.querySelector('#userAnswer').addEventListener('keydown', event => {
if(document.querySelector('p#feedBack').style.display == 'block')
document.querySelector('p#feedBack').style.display = 'none'
})
<button onclick="F1()"> New </button>
<label id="Z1"> </label>
<label id="operator1"> </label>
<label id="Z2"> </label>
= <input id="userAnswer" type="text" >
<button onclick="F2()">check</button>
<p id="feedBack"></p>
<p> <label id="answer"></label> </p>
Add to the F1-function
document.getElementById('feedBack').classList.add('hidden');
and to the CSS a new entry for the hidden class to hide the element if exists.
For displaying the feedback if check is pressed remove similar in F2 this class.
document.getElementById('feedBack').classList.remove('hidden');
function F1() {
Z1 = document.getElementById("Z1");
Z2 = document.getElementById("Z2");
rZ1 = Math.floor((Math.random() * 10));
rZ2 = Math.floor((Math.random() * 10));
Z1.innerHTML = rZ1;
Z2.innerHTML = rZ2;
var operators1 = ['+', '-'];
oper1 = document.getElementById("operator1");
op1 = operators1[Math.floor(Math.random() * 2)];
oper1.innerHTML = op1;
rnd = parseFloat(eval(rZ1 + op1 + rZ2));
answer.innerHTML = rnd;
document.getElementById('feedBack').classList.add('hidden');
}
function F2() {
antw = parseFloat(document.getElementById("userAnswer").value);
feedBack = document.getElementById("feedBack");
ant = document.getElementById("answer").textContent;
{
if (antw == ant) {
feedBack.textContent = "good";
} else {
feedBack.textContent = "bad";
}
}
document.getElementById('feedBack').classList.remove('hidden');
};
.hidden { visibility: hidden; }
<button onclick="F1()"> New </button>
<label id="Z1"> </label>
<label id="operator1"> </label>
<label id="Z2"> </label>
= <input id="userAnswer" type=text>
<button onclick="F2()">check</button>
<p id="feedBack"> </p>
<p> <label id="answer"></label> </p>

Calculate with formula javascript

Lately i want to make a converter formula with javascript. but i got a stack at this function
javascript
function UconverterDP(){
var inputD = document.getElementById('inputD').value;
var inputP = document.getElementById('inputP').value;
jikaP = inputD * 0.4;
bagianatasU1 = 0.8 * inputP * inputD;
bagianbawahU1 = P + (0.4 * inputD);
hasilU1 = bagianatasU1 / bagianbawahU1;
bagaianatasU2 = 0.8 * inputD;
bagaianatasU2a = 1 - bagaianatasU2 ;
bagaianatasU2h = inputP - bagaianatasU2a;
bagianbawahU2 = 0.0114 * inputP;
bagianbawahU2a = Math.pow(bagianbawahU2, 1.7);
bagianbawahU2b = 0.92 * bagianbawahU2a;
bagianbawahU2h = bagianbawahU1 * bagianbawahU2b;
hasilU2 = bagaianatasU2h / bagianbawahU2h;
if (inputP <= jikaP) {
document.getElementById("outputU").innerHTML = Hasil U1;
} else {
document.getElementById("outputU").innerHTML = hasilU2;
}
}
this my input
<tr>
<td>
<label>D : </label>
<input id="inputD" type="number" onchange="UconverterDP()">
</td>
<td>
<label>P : </label>
<input id="inputP" type="number" onchange="UconverterDP()" >
</td>
</tr>
and this output
<label> BUI (U): </label>
<span id="outputU"></span>
And this is the formula:
i really don t know if this is what are you searching, if it isn't tell me what is missing (and explain me a little bit more your idea):
<script>
function UconverterDP(){
var inputD = document.getElementById('inputD').value;
var inputP = document.getElementById('inputP').value;
jikaP = inputD * 0.4;
if (inputP <= jikaP) { // here your program choose what formula will use
var u =(0.8*inputP*inputD)/(inputP+0.4*inputD)// here is the first formula
document.getElementById("outputU").innerHTML = u;// and then here you return the value that you want
}
else {
var u = inputP-((1-0.8*inputD)/(inputP+0.4*inputD))/(0.92*0.0114*(inputP**1.7))// and here is the second formula
document.getElementById("outputU").innerHTML = u;// here is the same you return the value
}
}
// maybe you can do more short this code putting together the two "document.getElementById("outputU").innerHTML = u;" here, but work in this way also
</script>

Deactivate a button until all javascript conditions have been checked

I´m trying to do different javascript validations before sending a form, the problem is that I haven´t been able to prevent the form from submit, it checks the conditions and sends alerts when a conditions hasn´t been satisfied but it sends the form anyways. I want the button to either be disabled until everything is right or send a message telling user, to check the cuenta.
Thanks in advance. This is my code:
<form action="<?php echo base_url();?>index.php/Datos/agregar" method="post">
Enter CLABE account:
<input name="clabe" id="clabe" type = "text" pattern=".{17,17}" maxlength="17" required title="17 números exactamente"/>
<input type="text" name="control" id="control" maxlength="1" size="2" required >
Again:
<input name="clabe2" id="clabe2" type = "text" pattern=".{17,17}" maxlength="17" required title="17 números exactamente"/>
<input type="text" name="control2" id="control2" maxlength="1" size="2" required>
<hr>
Bank: <input type="text" name="Banco" id="Banco" readonly required onmousemove="comparaclabe();" >
<hr>
Observations: <input type="text" name="Observaciones" id="Observaciones" required>
<hr>
<input type="submit" id="myBtn" value="Guardar Cambios" onclick ="return compareclabe();" ><span id="msg"></span>
<hr>
<input type="hidden" id="cve_banco" name="cve_banco">
</form>
<hr>
<script>
function compareclabe(){
document.getElementById("myBtn").disabled = true;
var x1 = document.getElementById("clabe").value;
var x2 = document.getElementById("control").value;
var x3 = x1 + x2;
var z1 = document.getElementById("clabe2").value;
var z2 = document.getElementById("control2").value;
var z3 = z1 + z2;
if( x3 != z3){
alert("keys are not equal");
return false;
}else if (x3 == z3){
this.someFunc(); //I want to call function someFunc and then
if the result is true, execute the next code
if (true){
var cBanco = String(x3).charAt(0) + String(x3).charAt(1) + String(x3).charAt(2);
var x = cBanco;
switch (x) {
case "012":
text = "BBVA BANCOMER";
break;
case "014":
text = "SANTANDER";
break;
case "032":
text = "IXE";
break;
default:
text = "No value found";
}
document.getElementById("Banco").value = text;
document.getElementById("myBtn").disabled = false;
return true;
}
}else{
return false;
}
}
function someFunc() {
//myFunction2();
var x = document.getElementById("clabe2").value;
f2(x,'37137137137137137');
//return true;
}
function f2(a, b) {
var cad = Array.from(a, (v, i) => v * b[i] % 10).join('');
//se suman todos los digitos del array
var value = cad,
sum = value
.toString()
.split('')
.map(Number)
.reduce(function (a, b) {
return a + b;
}, 0);
//separate last digit from result
var number = sum;
// convert number to a string, then extract the first digit
var one = String(number).charAt(1);
// convert the first digit back to an integer
var one_as_number = Number(one);
var digito_control = (10 - one_as_number);
if (digito_control === 10 ) {
digito_control = 0;
var dg = digito_control;
}else{
dg = digito_control;
}
var z = document.getElementById("control2").value;
if (dg != z){
alert("checkig digit is not equal");
return false;
}
else if (dg == z){
alert("checkig digit is equal");
return true;
}
}
</script>
I changed form submit button type to "button" and if all the validations are passed, then submit form from javascript. See below code
function compareclabe() {
document.getElementById("myBtn").disabled = true;
var x1 = document.getElementById("clabe").value;
var x2 = document.getElementById("control").value;
var x3 = x1 + x2;
var z1 = document.getElementById("clabe2").value;
var z2 = document.getElementById("control2").value;
var z3 = z1 + z2;
if (x3 != z3) {
alert("keys are not equal");
return false;
} else if (x3 == z3) {
this.someFunc(); //I want to call function someFunc and then if the result is true, execute the next code
if (true) {
var cBanco = String(x3).charAt(0) + String(x3).charAt(1) + String(x3).charAt(2);
var x = cBanco;
switch (x) {
case "012":
text = "BBVA BANCOMER";
break;
case "014":
text = "SANTANDER";
break;
case "032":
text = "IXE";
break;
default:
text = "No value found";
}
document.getElementById("Banco").value = text;
document.getElementById("myBtn").disabled = false;
$('#form').submit(); //submit form if all validation succeeds
}
} else {
return false;
}
}
function someFunc() {
//myFunction2();
var x = document.getElementById("clabe2").value;
f2(x, '37137137137137137');
//return true;
}
function f2(a, b) {
var cad = Array.from(a, (v, i) => v * b[i] % 10).join('');
//se suman todos los digitos del array
var value = cad,
sum = value
.toString()
.split('')
.map(Number)
.reduce(function(a, b) {
return a + b;
}, 0);
//separate last digit from result
var number = sum;
// convert number to a string, then extract the first digit
var one = String(number).charAt(1);
// convert the first digit back to an integer
var one_as_number = Number(one);
var digito_control = (10 - one_as_number);
if (digito_control === 10) {
digito_control = 0;
var dg = digito_control;
} else {
dg = digito_control;
}
var z = document.getElementById("control2").value;
if (dg != z) {
alert("checkig digit is not equal");
return false;
} else if (dg == z) {
alert("checkig digit is equal");
return true;
}
}
<form action="<?php echo base_url();?>index.php/Datos/agregar" method="post" id="form"> <!-- I included an id to form -->
Enter CLABE account:
<input name="clabe" id="clabe" type="text" pattern=".{17,17}" maxlength="17" required title="17 números exactamente" />
<input type="text" name="control" id="control" maxlength="1" size="2" required> Again:
<input name="clabe2" id="clabe2" type="text" pattern=".{17,17}" maxlength="17" required title="17 números exactamente" />
<input type="text" name="control2" id="control2" maxlength="1" size="2" required>
<hr> Bank: <input type="text" name="Banco" id="Banco" readonly required onmousemove="comparaclabe();">
<hr> Observations: <input type="text" name="Observaciones" id="Observaciones" required>
<hr>
<input type="button" id="myBtn" value="Guardar Cambios" onclick="return compareclabe();"><span id="msg"></span>
<hr>
<input type="hidden" id="cve_banco" name="cve_banco">
</form>
<hr>
But there are many validation plugins where you can easily implement. No need to code from begining. Refer this for an example -> https://jqueryvalidation.org/
You can disable the button by default, and add event listeners to all the inputs in your form. But be weary of other ways to submit the form, like the enter key. I would add an onsubmit function just to prevent all ways the event can happen when you don't want it to.
const form = document.querySelector('form')
const inputs = [...form.querySelectorAll('input')] // convert node list to array
const isValid = () => {
let valid = false
disableButton()
// handle your conditions here
if (valid) enableButton()
return valid;
}
inputs.forEach( input => input.addEventListener('input', isValid))
form.onsubmit = event => if (!isValid()) event.preventDefault()
Or ES5 if you prefer:
var form = document.querySelector('form');
var inputNodes = form.querySelectorAll('input');
var inputs = Array.prototype.call.slice(inputNodes); // convert node list to array
var isValid = function() {
var valid = false;
disableButton();
// handle your conditions here
if (valid) enableButton();
return valid
}
inputs.forEach( function(input) {
input.addEventListener('input', isValid);
});
form.onsubmit = function(event) {
if (!isValid()) event.preventDefault();
};
It's also worth noting that HTML5 has a lot of built-in validation you can take advantage of.

javaScript got stuck with converting bytes

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">

Categories

Resources