What's the next step in creating a temp converter? - javascript

This is my very first time trying to create a simple program by using JS and I am a beginner, so please bear with me. I am here because I feel like I have all these pieces of code but I can't understand how to link them together. I have two functions inside the form that work on their own but I clearly need to link them to the result statement inside the if statement and I am not sure how to do that. Also, I am sure this is poorly written code but for now I am just focussing on having a working program. This is the JS code I have so far (HTML after that):
// grab elements & store in variable
const form = document.querySelector("form");
const submit = document.getElementById("submit");
const selectCelsius = document.getElementById("celsius")
const selectFahrenheit = document.getElementById("fahrenheit")
const result = document.getElementById("result");
const userInput = document.getElementById("userInput").value
form.addEventListener("submit", (e) => {
e.preventDefault();
const fahrenheit = (c) => {
let f = (c * 9/5) + 32
return f
}
const celsius = (f) => {
let c = ((f - 32) * 5) - 9
return c
}
if (selectCelsius === "Celsius" && submit.innerHTML === "CONVERT") {
return result.innerHTML = "Your result is " + userInput(fahrenheit)
}
if (selectFahrenheit === "Fahrenheit" && submit.innerHTML === "CONVERT") {
return result.innerHTML = "Your result is " + userInput(celsius)
}
})
HTML:
<body>
<div class="main-wrapper">
<div class="sub-wrapper">
<div class="weather">
<img src="./img/weather.png" alt="weather">
<h1>temperature converter</h1>
</div>
<form action="#">
<input type="number" id="userInput" name="temperature" placeholder="temperature">
<select name="temperature" id="temperature">
<option value="celsius" id="celsius">Celsius</option>
<option value="fahrenheit" id="fahrenheit">Fahrenheit</option>
</select>
<input type="submit" id="submit" value="CONVERT"></input>
</form>
<p id="result"></p>
</div>
</div>
<script src="./app.js"></script>
</body>

There are a couple of issues with your code.
First of all, you are accessing the values of user-input at the time of the application-load, hence when the user makes any changes in the input box and submits, the value entered by the user doesn't reach javascript.
The logical check applied inside the submit event's callback function are not correct. You need to access the value of the select element which has id temperature.
The function invocation for calculating the conversion was also wrong in your case. Function invocation follows <function-name>(<argument>) pattern. Hence it should be fahrenheit(userInput) instead of userInput(fahrenheit). and similarly celsius(userInput)
Following changes in the js code should give you the expected outcome.
// grab elements & store in variable
const form = document.querySelector("form");
const submit = document.getElementById("submit");
const result = document.getElementById("result");
form.addEventListener("submit", (e) => {
e.preventDefault();
const userInput = document.getElementById("userInput").value;
const selectTemperature = document.getElementById("temperature").value;
const fahrenheit = c => {
let f = (c * 9) / 5 + 32;
return f;
};
const celsius = f => {
let c = (f - 32) * 5 - 9;
return c;
};
if (selectTemperature === "celsius") {
result.innerHTML = "Your result is " + fahrenheit(userInput);
}
if (selectTemperature === "fahrenheit") {
result.innerHTML = "Your result is " + celsius(userInput);
}
})
Here is a link to my solution: https://stackblitz.com/edit/js-kruqd1

Related

how to call a function with a submit element [duplicate]

This question already has answers here:
Why can't I get the input from the input box?
(6 answers)
Closed 1 year ago.
I'm trying to call a function using an event listener but for some reason, it won't work. I'm not getting any errors in my javascript or HTML, so what's the deal?
// Data
const clicks = document.getElementById('loc');
const input = document.getElementById('input').value;
const check = document.getElementById('check');
var totalClicks = 0;
var wToType = "var loc = 0";
// functions
function checkCode() {
if (input === wToType) {
totalClicks += 1
clicks.textContent = "Lines of code:" + totalClicks;
}
};
// Event listeners
check.addEventListener("click", checkCode, false);
<h1 id="loc">Lines of code: 0</h1><br><br>
<h3 id="wtt">Lets get started with our loc (lines of code) variable. Type "var loc = 0"</h3>
<input type="text" name="myInput" id="input" size="25" required>
<input type="submit" id="check" value="Write line(s) of code">
Write
const input = document.getElementById('input')
in the line 2, and
input.value == wToType
in line 11.
It's better to take the value from your input right during calling the function.
Here is the right JS code:
// Data
let clicks = document.getElementById('loc');
const check = document.getElementById('check');
let totalClicks = 0;
let wToType = "var loc = 0";
// functions
function checkCode() {
const input = document.getElementById('input').value;
if(input === wToType) {
totalClicks += 1
clicks.textContent = "Lines of code: " + totalClicks;
}
};
// Event listeners
check.addEventListener("click", checkCode, false);

I was practicing a way to loop numbers to create a times table but the loop only runs one time

I am practicing creating a function that loops whatever number I put into the input into a times table. I used a for loop to achieve this but I ran into an issue. My for loop only runs one time and it only get my input * 10 for some reason. Can someone please help. Thank you.
function myFunction() {
var inputNumber = document.querySelector(".input-field").value;
inputNumber = parseInt(inputNumber);
if (isNaN(inputNumber) || inputNumber == "" || inputNumber == null) {
document.querySelector(".output h1").innerHTML = "Please enter a number!";
} else {
for (i = 1; i <= 10; i++) {
let product = inputNumber * i;
document.querySelector(".output").innerHTML = "<br>" + inputNumber + " * " + i + " = " + product + "<br>";
}
}
}
Looks like you update the HTML on every iteration. However, I think you want to expand the innerHTML to include all elements?
I would look into creating html elements in javascripts and adding them in html like this (draft, untested):
const element = document.createElement("div")
for (let i = 1; i < 10; i++) {
let product = inputNumer * i;
element.appendChild(document.createTextNode(`${inputNumer} ${product}`);
}
Please study this. It is using recommended event listener and a map
const arr = [...Array(11).keys()].slice(1); // numbers from 1 to 10
const h1 = document.querySelector("#output h1"),
result = document.getElementById("result"),
inputField = document.getElementById("inputField");
inputField.addEventListener("input", function() {
const inputNumber = +this.value;
console.log(inputNumber)
h1.classList.toggle("hide", inputNumber); // keep hide if ok number
result.innerHTML = inputNumber ? arr.map(i => `${inputNumber} * ${i} = ${inputNumber*i}`).join(`<br/>`) : "";
});
.hide {
display: none;
}
<input type="number" id="inputField" class=".input-field" />
<hr/>
<div id="output">
<h1 class="error hide">Please enter a number!</h1>
<div id="result">
</div>
</div>

How to populate multiple HTML DOM elements with local storage values

I want to display contents in the last <div> element when a click event occurs but now it only shows 1st 2 elements. Is there something I am not doing right somewhere?
Here is my code so far:
JS
const iname = document.getElementById("name");
const iemail = document.getElementById("email");
const iphone = document.getElementById("phone");
const submit = document.getElementById("submit");
const storage = document.getElementById("storage");
submit.onclick = function () {
const name = iname.value;
const email = iemail.value;
const phoneno = iphone.value;
if (name && email && phoneno) {
localStorage.setItem(name, "");
localStorage.setItem(email, "");
localStorage.setItem(phoneno, "");
location.reload();
}
};
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
storage.innerHTML += `Name : ${key}<br />Email : ${value}`;
}
localStorage.clear()
HTML
<p>Name</p>
<input id="name" autocomplete="off">
<p>Email</p>
<input id="email" autocomplete="off">
<p>Phone no</p>
<input id="phone" autocomplete="off">
<button id="submit">Let's go</button>
<div id="storage" class="box">
<h1>Is this correct?</h1></div>
I think you are setting the values in localstorage the wrong way.
The syntax for storing stuff in there is localstorage.setItem(keyName, keyValue).
And your code is setting the keyName argument to the value you are getting from the form and keyValue argument to an empty string; not what you need.
Make the following changes and you should be good to go (see comments):
submit.onclick = function () {
const name = iname.value;
const email = iemail.value;
const phoneno = iphone.value;
if (name && email && phoneno) {
// set local storage values
localStorage.setItem("name", name); // modified
localStorage.setItem("email", email); // modified
localStorage.setItem("phoneno", phoneno); // modified
location.reload();
}
console.log(localStorage); // new (maybe unnecessary)
};
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
storage.innerHTML += `${upFirst(key)}: ${value}<br>`; // modified
}
localStorage.clear();
/**
* new: making the first letter an upper case (for labels in the output div).
* See usage in 'for loop' above.
*/
function upFirst(stringValue) {
return stringValue.slice(0, 1).toUpperCase() + stringValue.slice(1);
}

The sum cannot show although i click on the button

What I want is, after the user enters the number of subjects, the system will show the number of input box according to the number of subjects entered, then when the user clicks on the button, it should show the sum. I tried many ways, but I failed to show the sum, anyone knows what is the mistake I made?
Below is my code:
function select() {
var x = parseInt(document.getElementById('1').value);
if (document.getElementById('1').value == "") {
alert("Please fill up number of subject");
} else if (isNaN(x) == true) {
alert("Please fill up number of subject with number");
} else {
var subject = parseInt(document.getElementById('1').value);
var sum = 0;
for (var num = 1; num <= subject; num++) {
document.write("Enter the mark for subject " + num + " : ");
var value = parseFloat(document.write("<input/><br>"));
sum += value;
}
var calc = document.write("<button>Next</button><br>");
calc.onclick = function() {
next()
};
function next() {
document.write("Total marks: " + sum + "%");
}
}
}
<html>
<body>
Enter the number of subject: <input type="text" onkeypress="return/[0-9]/i.test(event.key)" id="1" value=""><br>
<button onclick="select()">Check</button><br>
</body>
</html>
That's how I have rewritten a big part of your code. I have place inline comments to explain what I do.
function select() {
var x = parseInt(document.getElementById('1').value, 10);
// Getting the div that wraps the initial form.
var formWrapper = document.querySelector('.formWrapper');
// Getting the div, that is going to display the new fields and the results.
var results = document.querySelector('.results');
// I have switch your statement from x == '' to '' === x as it
// consists a good practice
if ( '' === x ) {
alert("Please fill up number of subject");
// I have remove the isNaN(x) == true, because the isNan will
// be either true or false.
} else if ( isNaN(x) ) {
alert("Please fill up number of subject with number");
} else {
// Using parseInt(x, 10) to set the base.
var subject = parseInt(x, 10);
// In this array, I store the auto-generated fields.
var fieldsList = [];
// Removing the first div from the DOM
formWrapper.parentElement.removeChild(formWrapper);
for ( var num = 1; num <= subject; num++ ) {
// I am creating a new field
var newField = document.createElement('input');
// I push the field into the array I made for the fields.
fieldsList.push(newField);
// I append the field in the HTML
results.appendChild(newField);
// I create a <br> tag
var br = document.createElement('br');
// And I append the tag in the DOM
results.appendChild(br);
}
// I create the button that is going to handle the Next functionality
var nextButton = document.createElement('button');
// I set the button text
nextButton.innerText = 'Next';
// I add an Event Listener for the click event.
nextButton.addEventListener(
'click',
function() {
// I reset the sum to 0
var sum = 0;
// I itterate the fields auto-generated and saved in the array
fieldsList.forEach(
function(field) {
// I get the value
sum += parseInt(field.value, 10);
}
);
// I create the field that is going to display the output
let resultText = document.createElement('div');
// I set the text based on the sum
resultText.innerText = "Total marks: " + sum + "%";
// I append the text message to the DOM
results.appendChild(resultText);
}
);
// I append the button to the DOM
results.appendChild(nextButton);
}
}
<html>
<body>
<div class="formWrapper">
Enter the number of subject: <input type="text" onkeypress="return/[0-9]/i.test(event.key)" id="1" value=""><br>
<button onclick="select()">Check</button><br>
</div>
<div class="results"></div>
</body>
</html>

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.

Categories

Resources